Java语言的反射机制,我们可以理解为:在运行状态中,对于任意一个实体类或对象,我们可以获取这个类的所有属性和方法。正因如此,使得Java的反射机制在流行框架如Spring、hibernate、MyBatis,设计模式如工厂模式、动态代理等应用广泛,当然JDK中也有许多底层代码也是灵活地运用了反射机制。本文和大家一起探讨学习Java语言的反射机制,主要介绍在运行时对某个类对象信息如类名、变量、方法等等的获取,也编程实现了一个简单的动态代理实例。
一、通过反射获取类相关信息
编写一个User类,并定义相关属性和方法:
package com.ldl.reflection;
public class User {
private String name = "BoA";
public int age = 18;
public User(){
}
private void say(){
System.out.println("private method --- HelloWorld");
}
public void study(){
System.out.println("public method --- Java");
}
}
编写测试类,通过反射获取类相关信息:
package com.ldl.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestReflection {
public static void main(String[] args) throws Exception {
User t = new User();
Class class1 = t.getClass();
String className = class1.getName();
System.out.println("className:"+className);
Field[] fields = class1.getFields();
for (Field field : fields) {
System.out.println("get public field:"+field);
}
Field[] fields2 = class1.getDeclaredFields();
for (Field field : fields2) {
System.out.println("get all field:"+field);
}
Field field = class1.getField("age");
System.out.println(field);
Field field2 = class1.getDeclaredField("name");
field2.setAccessible(true);
System.out.println(field2);
Method[] methods = class1.getMethods();
for (Method method : methods) {
System.out.println("get public method:"+method.getName());
}
Method[] methods2 = class1.getDeclaredMethods();
for (Method method : methods2) {
System.out.println("get all method:"+method);
}
Constructor[] constructors = class1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println("get constructor:"+constructor);
}
Object tObject = class1.newInstance();
field2.set(tObject, "JAVA1995");
System.out.println(field2.get(tObject));
}
}
运行效果:
通过上述实例,我们可以发现,通过反射机制,可以获取类相关的诸多信息:类名、公有属性、私有属性、公有方法、私有方法、构造方法等。
二、通过反射获取父类相关信息
首先我们定义一个父类Parent:
package com.ldl.reflection;
public class Parent {
public String publicField = "parent_publicField";
protected String protectField = "parent_protectField";
String defaultField = "parent_defaultField";
private String privateField = "parent_privateField";
}
编写子类Son继承Parent类:
package com.ldl.reflection;
public class Son extends Parent{
}
测试获取父类的相关信息:
package com.ldl.reflection;
import java.lang.reflect.Field;
public class TestReflectionForSupper {
public static void main(String[] args) throws Exception {
Class c1 = Class.forName("com.ldl.reflection.Son");
System.out.println(getFieldValue(c1.newInstance(),"publicField"));
System.out.println(getFieldValue(c1.newInstance(),"protectField"));
System.out.println(getFieldValue(c1.newInstance(),"defaultField"));
System.out.println(getFieldValue(c1.newInstance(),"privateField"));
}
public static Field getDeclaredField(Object obj,String fieldName) {
Field field = null;
Class c = obj.getClass();
for(; c != Object.class ; c = c.getSuperclass()){
try {
field = c.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
}catch (Exception e){
}
}
return null;
}
public static Object getFieldValue(Object object,String fieldName) throws Exception{
Field field = getDeclaredField(object,fieldName);
return field.get(object);
}
}
运行效果:
这样,我们就能够获取到父类的各种属性(包含私有属性)了。
三、通过反射生成动态代理
编写代理接口:
package com.ldl.proxy;
public interface MyProxyInterface {
public void say(String str);
}
代理类实现代理接口:
package com.ldl.proxy;
public class MyProxy implements MyProxyInterface{
@Override
public void say(String str) {
System.out.println("Hello " + str);
}
}
动态代理类:
package com.ldl.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicProxy implements InvocationHandler{
private Object proxy;
public DynamicProxy(Object proxy) {
this.proxy = proxy;
}
public Object invoke(Object object, Method method, Object[] args) throws Throwable {
method.invoke(proxy, args);
return null;
}
}
测试动态代理:
package com.ldl.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class TestProxy {
public static void main(String[] args) {
MyProxyInterface realProxy = new MyProxy();
InvocationHandler handler = new DynamicProxy(realProxy);
MyProxyInterface subject = (MyProxyInterface) Proxy.newProxyInstance(handler.getClass().getClassLoader(), realProxy.getClass().getInterfaces(), handler);
subject.say("World!");
}
}
运行效果:
本文通过以上简单的Demo对Java语言的反射机制编码实践。理解反射机制并且能够灵活运用,会让大家编写出更高效率的代码和更优秀的程序!