1、什么是反射?
反射是一种计算机处理方式。有程序可以访问、检测和修改它本身状态或行为的这种能力;
通俗点讲,反射是程序中的一种能力;
2、反射可以干什么?
反射可以通过类的名字可以获取这个类的信息(类名,方法名,属性名,即可以调用这个方法。。。)
3、反射的核心?
反射的核心就是将类本身当成一个对象,通过Class类,进行获取,处理
3、写的demo如下:
package springaop.impl;
import springaop.IUserService;
public class UserServiceImpl implements IUserService{
@Override
public void add() {
System.out.println("add name!");
}
public void set(){
System.out.println(" wo shi set!");
};
}
package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestRefect {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
//加载类
Class<?> clazz = Class.forName("springaop.impl.UserServiceImpl");
//获取方法
Method method = clazz.getMethod("add");
Object invoke = method.invoke(clazz.newInstance());
System.out.println("==="+method.invoke(clazz.newInstance())+"===//"+invoke);
}
}
结果返回
add name!
add name!
===null===//null