ReflectTest

package com.djwl.test.studying;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ReflectTest {

public static void main(String args[]) {
try {
Class<?> c = Class.forName("com.djwl.test.studying.TestReflect");
System.out.println(c);
System.out.println("`````````````````````````````````````````````");
// 構造方法
System.out.println("\n\n=======構造方法:");
Constructor<?> cts[] = c.getDeclaredConstructors();
for (Constructor<?> ct : cts) {
System.out.println("``````````````````");
System.out.println("ct: " + ct.toString());
System.out.println("name: " + ct.getName());
System.out.println("ct class:" + ct.getDeclaringClass());
for (Class<?> class1 : ct.getParameterTypes()) {
System.out.println("param:" + class1);
}
for (Class<?> class1 : ct.getExceptionTypes()) {
System.out.println("exc:" + class1);
}
}

// 方法信息
System.out.println("\n\n=======方法信息:");
Method m[] = c.getDeclaredMethods();
for (Method method : m) {
System.out.println("``````````````````");
System.out.println("method: " + method.toString());
System.out.println("name: " + method.getName());
System.out.println("getDeclaringClass:" + method.getDeclaringClass());
for (Class<?> class1 : method.getParameterTypes()) {
System.out.println("param: " + class1);
}
for (Class<?> class1 : method.getExceptionTypes()) {
System.out.println("exception: " + class1);
}
System.out.println("return: " + method.getReturnType());
}

// 獲取類的字段(域)
System.out.println("\n\n=======字段信息:");
for (Field fld : c.getDeclaredFields()) {
System.out.println("name = " + fld.getName());
System.out.println("decl class = " + fld.getDeclaringClass());
System.out.println("type = " + fld.getType());
int mod = fld.getModifiers();
System.out.println("modifiers = " + Modifier.toString(mod));
System.out.println("-----");
}

// 根據方法的名稱來執行方法
System.out.println("\n\n=======根據方法的名稱來執行方法:");
Class[] paramTypes = new Class[2];
paramTypes[0] = Integer.TYPE;
paramTypes[1] = Integer.TYPE;
Method method = c.getMethod("add", paramTypes);

Object[] argList = new Object[2];
argList[0] = new Integer(37);
argList[1] = new Integer(43);

ReflectTest t = new ReflectTest();
Object returnObj = method.invoke(t, argList);
Integer returnVal = (Integer) returnObj;

System.out.println("方法執行結果爲:" + returnVal.intValue());
} catch (Throwable e) {
System.err.println(e);
}
}

public ReflectTest() {

}

public ReflectTest(String id) {

}

public ReflectTest(String id, String password, Integer age) throws IOException, FileNotFoundException {

}

public void update() {

}

public String getName() {
return "xiaoming";
}

public Integer getAge(String userid) throws IOException {
return 0;
}

public int add(int a, int b) {
return a + b;
}

private String name;
private String password;
public Integer age;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章