ava 反射机制
class=class.forName(“”)
class= aa.getClass(); user aa=new user();
class=user.class;
报名.类名$内部类
Class<?> clazz = Class.forName("test.aa$b");
实例化:
Class a=Class.forName("Reflection.Ship");
Class[] c={String.class, int.class}; //new Class[] { String.class, String.class }
Constructor con=a.getConstructor(c); con.setAccessible(true);
Object obj=con.newInstance("asd",12);
c.newInstance(new Outer()) 实例化内部类要加类的实例化
获取方法,变量:
c.getDeclaredFields();
fields[i].getType() == By.class
fields[i].getName() 拿名
fields[i].get(aa); 拿值 //实例化的aa
c.getDeclaredMethods();
执行方法:
clazz = Class.forName(className);
Object o = clazz.newInstance();
Method[] ms = clazz.getDeclaredMethods();
for (Method m : ms) {
if (m.getName().equals(methodName)) {
m.invoke(o);
}
}
执行方法返回值:
Class cls = Class.forName("com.common.page."+classname);
Method m = cls.getDeclaredMethod("By",String.class);
String aa= m.invoke(cls.newInstance(),value);
修改变量:
clazz = Class.forName(className);
Field field=clazz.getDeclaredField(filedName);
field.setAccessible(true);
field.set(filedName,changed);