最近看框架的時候發現自己的反射的知識不是特別清楚,隨即就抽了點時間在網上把反射的知識補了一下,下面是我自己敲的一個小案例,見笑見笑
package com.yc.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import com.yc.entity.Employee;
public class MyReflection {
public static void main(String[] args) {
// Employee e=new Employee();
// System.out.println(e);
// e=new MyReflection().invokeTest(Employee.class);
// System.out.println(e);
// new MyReflection().testForName("com.yc.entity.Employee");
List<String> methodStrs=new MyReflection().showMethod(String.class);
for (String s : methodStrs) {
System.out.println(s);
}
}
public void testForName(String path){
try {
Class<?> c=Class.forName(path);
System.out.println(c.newInstance() instanceof Employee);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> T invokeTest(Class c){
T t = null;
try {
t=(T) c.newInstance();
//類或接口聲明的所有方法,包括公共、保護、默認(包)訪問和私有方法,但不包括繼承的方法。當然也包括它所實現接口的方法。
Method[] ms=t.getClass().getDeclaredMethods();
for (Method m : ms) {
/*if(m.getName().equals("toString")){
m.invoke(t);
}*/
if(m.getName().startsWith("set")){
Class<?>[] types = m.getParameterTypes();
if((types[0].getSimpleName()).equals("String")){
m.invoke(t,"66666");
} else if((types[0].getSimpleName()).equals("int")){
m.invoke(t,2);
}
}
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return t;
}
//顯示所有的方法
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> List<String> showMethod(Class c){
List<String> methodStrs=new ArrayList<String>();
T t;
try {
//實例化所給的類
t=(T) c.newInstance();
//返回某個類的所有公用(public)方法包括其繼承類的公用方法,當然也包括它所實現接口的方法。
//Method[] ms=t.getClass().getMethods();
//對象表示的類或接口聲明的所有方法,包括公共、保護、默認(包)訪問和私有方法,但不包括繼承的方法。當然也包括它所實現接口的方法。
Method[] ms=t.getClass().getDeclaredMethods();
String str;
for (Method m : ms) {
//獲取方法的修飾符
str=Modifier.toString(m.getModifiers())+" ";
//獲取返回類型
Class<?> returnType=m.getReturnType();
str+=returnType.getSimpleName()+" "+m.getName()+"(";
//獲取形參類型
Class<?>[] types=m.getParameterTypes();
if(types.length>0){
for (int i=0;i<types.length;i++) {
//獲取類型名,不是全限定名
str+=types[i].getSimpleName()+" "+"arg"+i+",";
}
str=str.substring(0, str.lastIndexOf(","));
}
str+=")";
//獲取拋出的異常
Class<?>[] exceptions=m.getExceptionTypes();
if(exceptions.length>0){
str+=" throws ";
for (Class<?> e : exceptions) {
str+=e.getSimpleName()+",";
}
str=str.substring(0, str.lastIndexOf(","));
}
str+="{}";
methodStrs.add(str);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return methodStrs;
}
}
貼上showMethod方法的測試結果