Java反射机制主要提供了以下功能: 在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理。
public class Message {
public static final String CODE_0000 = "错误码0000";
public static final String CODE_0001 = "错误码0001";
public static final String CODE_0002 = "错误码0002";
public static final String CODE_0003 = "错误码0003";
public Message(String a){
this.getMessageMethod("hello");
}
public Message(){
this.getMessageMethod("nothing");
}
public String getMessageMethod(String param) {
return "this is getMessageMethod.and param is " + param;
}
public String getMessageMethod(String param, int i) {
return "this is getMessageMethod.Param is " + param + "," + i;
}
}
测试类:
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws Exception {
Class clazz=Class.forName("test.Message");// 这里写清楚包名.类名,否则会找不到
System.out.println("---↓---Value-Of-\"CODE_0000\"---↓---");
Object obj=clazz.newInstance();
Field fid=clazz.getField("CODE_0000");
System.out.println(fid.get(obj));
System.out.println("--↓--Use-Method-\"getMessageMethod(String)\"--↓--");
String methodName = "getMessageMethod";
Method method = clazz.getMethod(methodName,String.class);
Object value = method.invoke(clazz.newInstance(),"hello");
System.out.println( value.toString());
System.out.println("--↓--Use-Method-\"getMessageMethod(String,int)\"--↓--");
method = clazz.getMethod(methodName,String.class,int.class);
value = method.invoke(clazz.newInstance(),"hello",2);
System.out.println( value.toString());
System.out.println("---↓---getDeclaredFields---↓---");
Field[] fields=clazz.getDeclaredFields();
for(int i=0;i<fields.length;i++){
System.out.println(fields[i].getName()+":"+fields[i].get(clazz.newInstance()));
}
System.out.println("---↓---getDeclaredMethods---↓---");
Method[] declaredMethods=clazz.getDeclaredMethods();
for(int i=0;i<declaredMethods.length;i++){
System.out.println(declaredMethods[i].getName());
}
System.out.println("---↓---getMethods---↓---");
Method[] methods=clazz.getMethods();
for(int i=0;i<methods.length;i++){
System.out.println(methods[i].getName());
}
System.out.println("---↓---getConstructors---↓---");
Constructor[] constructor=clazz.getConstructors();
for(int i=0;i<constructor.length;i++){
System.out.println(constructor[i].toString());
}
}
}
---↓---Value-Of-"CODE_0000"---↓---
错误码0000
--↓--Use-Method-"getMessageMethod(String)"--↓--
this is getMessageMethod.and param is hello
--↓--Use-Method-"getMessageMethod(String,int)"--↓--
this is getMessageMethod.Param is hello,2
---↓---getDeclaredFields---↓---
CODE_0000:错误码0000
CODE_0001:错误码0001
CODE_0002:错误码0002
CODE_0003:错误码0003
---↓---getDeclaredMethods---↓---
getMessageMethod
getMessageMethod
---↓---getMethods---↓---
getMessageMethod
getMessageMethod
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
---↓---getConstructors---↓---
public test.Message(java.lang.String)
public test.Message()