Java反射
Java反射技术应用广泛,它能够配置:类的全限定名、方法和参数,完成对象的初始化,甚至是反射某些方法,大大增强Java的可配置性。包括对象构建、反射方法、注解、参数、接口等,以下主要测试对象构建和方法的反射调用。
通过反射构建对象
java中允许通过配置反射信息构建对象。以下面代码为例,通过类加载器注册了类的全限定名,通过newInstance()方法初始化一个对象。
若构造器不携带参数:
/** 构造器无参数反射
* @author Jiayuan
* @version 1.0
* @description:
* @time 11/24/2018 10:55 AM
*/
public class ReflectServiceImp1 {
public void sayHello(String name){
System.out.println("Hello "+name);
}
@Test
public void getInstance(){
ReflectServiceImp1 object = null;
try{
object = (ReflectServiceImp1) Class.forName("framework.reflect.ReflectServiceImp1").newInstance();
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException ex){
ex.printStackTrace();
}
object.sayHello("test");
// return object;
}
}
若构造器携带参数:
/** 构造器带参数类反射
* @author Jiayuan
* @version 1.0
* @description:
* @time 11/24/2018 11:03 AM
*/
public class ReflectServiceImp2 {
private String name;
public ReflectServiceImp2(){}
public ReflectServiceImp2(String name){
this.name = name;
}
public void sayHello(){
System.out.println("hello "+name);
}
public static ReflectServiceImp2 getInstance(){
ReflectServiceImp2 object = null;
try{
object = (ReflectServiceImp2) Class.forName("framework.reflect.ReflectServiceImp2").getConstructor(String.class).
newInstance("test");
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException
| SecurityException | IllegalArgumentException | InvocationTargetException ex){
ex.printStackTrace();
}
object.sayHello();
return object;
}
public static void main(String[] args) {
ReflectServiceImp2.getInstance();
}
}
先通过forName加载到类的加载器,然后通过getConstructor方法,它的参数可以是多个,这里定义为String.class,有且只有一个参数类型为String的构造方法,通过这个方法对重名方法进行排除,再用newInstance方法生成对象,不过此时需要添加构造器参数(代码中的“test”),通过反射机制生成对象。
反射方法
在使用方法方法前要获取方法对象,得到了方法才能去反射。
/** 反射方法
* @author Jiayuan
* @version 1.0
* @description:
* @time 11/24/2018 11:03 AM
*/
public class ReflectServiceImp2 {
public void sayHello(String name){
System.out.println("hello "+name);
}
public Object reflectMethod(){
Object returnObj = null;
ReflectServiceImp2 target = new ReflectServiceImp2();
try{
Method method = ReflectServiceImp2.class.getMethod("sayHello",String.class);
returnObj = method.invoke(target,"test");
}catch(NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException |
InvocationTargetException ex){
ex.printStackTrace();
}
return returnObj;
}
public static void main(String[] args) {
new ReflectServiceImp2().reflectMethod();
}
}
运行结果均如下:
对象在反射机制下生成后,反射了方法,这样我们完全可以通过配置来完成对象和方法的反射,增强Java的可配置性和可扩展性。