Java反射
Java反射技术使用广泛,它能够配置:类的全限定名,方法和参数,完成对象的初始化,甚至反射某些方法。大大提高Java的可配置性,Spring Ioc的基本原理也是如此。
反射核心:class类,对于Java类都是class类对象。反射以class类为基础构建,涉及java类加载器。
反射的实现:java.lang.reflect.* ; 通过该包来实现。
重点:
- 通过类加载器加载某个类的全限定名来创建该类的对象。
Class.forName(“类的全限定名”) 返回值为该类的class对象
Class对象.newInstance(); 返回该类的对象。
//反射方式来实例化对象 方法之一
object = (ReflectServiceImpl) Class.forName("com.lean.ssm.chapter2.reflect.ReflectServiceImpl")
.newInstance();
注:获取一个类的class对象方法很多:
例如 该类类名.getClass();
该类的对象.getClass();
- 通过class类的对象来获取并调用方法。
//获取方法
Method method = ReflectServiceImpl.class.getMethod("sayHello", String.class);
//调用方法
returnObj = method.invoke(target, "张三");
实例说明:
//创建普通类,然后设法利用反射来使用该方法
public class ReflectServiceImpl {
public void sayHello(String name) {
System.err.println("Hello " + name);
}
}
//利用反射来实例化、调用方法。
public class ReflectTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ReflectTest test = new ReflectTest();
test.reflectMethod();
// ReflectServiceImpl reflect = test.getInstance();
// reflect.sayHello("你妹!");
}
//反射实例化
public ReflectServiceImpl getInstance() {
ReflectServiceImpl object = null;
try {
object = (ReflectServiceImpl) Class.forName("com.lean.ssm.chapter2.reflect.ReflectServiceImpl")
.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
ex.printStackTrace();
}
return object;
}
//反射调用方法
public Object reflectMethod() {
Object returnObj = null;
ReflectServiceImpl target = new ReflectServiceImpl();
try {
Method method = ReflectServiceImpl.class.getMethod("sayHello", String.class);
returnObj = method.invoke(target, "张三");
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException ex) {
ex.printStackTrace();
}
return returnObj;
}
public Object reflect() {
ReflectServiceImpl object = null;
try {
object = (ReflectServiceImpl) Class.forName("com.lean.ssm.chapter2.reflect.ReflectServiceImpl")
.newInstance();
Method method = object.getClass().getMethod("sayHello", String.class);
method.invoke(object, "张三");
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
ex.printStackTrace();
}
return object;
}
}