正常创建对象是new一个对象,反射是在引用的类无法满足现有需求的情况下,加载类,调用方法,创建对象 ,最大的作用是可以调用私有方法。
- class类:代表java中的类或接口,通过class可以调用构造方法,类,方法等信息
- constructor类:代表类的构造函数,通过constructor类,可以创建对象
- method类:可以调用方法
- field类:可以修改字段
class.forname(全限定名):怎么定义,路径的地址应该怎么写???路径中间是.(点)
获取全限定类名的方法:
Class c = refla.class;
String classname = c.getName();
System.out.println(classname);
Java反射常用到的方法:
1)获取类的三种方法:
通过类名.class获取
Class c = refla.class;
通过class.forname获取
Class c = Class.forName(“test.refla”);
通过对象.getclass获取
Class c = new refla().getClass();
2)获取方法:
getMethods 获取公共方法
getDeclaredMethods 获取所有非public的方法
Method[] method1 = c.getMethods();
for(Method method:method1){
System.out.println(method.getName());
}//输出public的方法信息
3)创建对象:
通过class对象的newInstance 创建对象
Class c = refla.class;
refla refla = (test.refla) c.newInstance();
通过 Constructor 对象的 newInstance() 方法
Class c = refla.class;
Constructor constructor = c.getConstructor();
refla refla = (test.refla) constructor.newInstance();
通过构造器可以调用有参构造函数
Class clz = Apple.class;
Constructor constructor = clz.getConstructor(String.class, int.class);
Apple apple = (Apple)constructor.newInstance("红富士", 15);
public class Apple {
private int price;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public static void main(String[] args) throws Exception{
//正常的调用
Apple apple = new Apple();
apple.setPrice(5);
System.out.println("Apple Price:" + apple.getPrice());
//使用反射调用
Class clz = Class.forName("com.chenshuyi.api.Apple");//获取类
Method setPriceMethod = clz.getMethod("setPrice", int.class);//根据类获取方法,参数类型.class
Constructor appleConstructor = clz.getConstructor();//获取构造器
Object appleObj = appleConstructor.newInstance();//创建对象
setPriceMethod.invoke(appleObj, 14);
Method getPriceMethod = clz.getMethod("getPrice");
System.out.println("Apple Price:" + getPriceMethod.invoke(appleObj));//invoke调用方法
}
}
反射调用私有方法
package test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class refla {
private double price;
private void test(){
System.out.println("测试价格");
}
public static void main(String[] args) throws Exception {
Class c = Class.forName("test.refla");
Method method = c.getDeclaredMethod("test");
// Constructor constructor = c.getConstructor();
Object o = c.newInstance();
method.invoke(o);
}
}