利用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();
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq_25667339/article/details/52294807
内容来源于网络,如有侵权,请联系作者删除!