java反射机制动态给属性赋值

x33g5p2x  于2021-11-22 转载在 Java  
字(0.9k)|赞(0)|评价(0)|浏览(361)

利用java的reflection机制,动态的给类中的变量赋值。

try {
   Class cls = Class.forName("com.zhjx.bean.User");
   Method mtd = cls.getMethod("setUsername", new Class[]{String.class});
   Object obj = (Object)cls.newInstance();
   mtd.invoke(obj, new Object[]{"Erica"});
   System.out.println(((User)obj).getUsername());
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SecurityException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (NoSuchMethodException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InstantiationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

相关文章

最新文章

更多