Reflection
A way for a program/application to learn about itself, change itself, and perhaps even add to itself.
//获取className的三种方法
Datedate=newDate();
Class<?>clazz=date.getClass();
Class<?>clazz1=Date.class();
Class<?>clazz2=Class.forName("java.lang.Object");
/**
* java.lang.Class
* The java.lang.Class class instance represent classes and interfaces in a running Java application.
*/
//运行时创建对象,传参数和不传参数
//Class.newInstance();
Class<?>clazz=Class.forName("cn.tju.scs.c03.reflection.CarRef");
Objectobj=clazz.newInstance();
//Constructor.newInstance(para1,para2);
Constructor<?>con=clazz.getConstructor(String.class,double.class);
Objectobj=con.newInstance("大众",20.3);
//invoke method
Classclazz=Teacher.class;
Personteacher=newTeacher();
Methodm0=clazz.getMethod("toString");
//参数不同 名字相同overload
Methodm1=clazz.getMethod("eat",String.class);
Methodm2=clazz.getMethod("eat",String.class,int.class);
m0.invoke(teacher);
//改变变量
Class<?>clazz=Class.forName("cn.tju.scs.c03.reflection.CarMethod");
Objectobj=clazz.newInstance();
FieldnameField=clazz.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(obj,"红旗");
When a method in a Class will be invoked?
– Reflection
– Clone
– New
网友评论