Java反射機制,java反射
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
Scanner in = new Scanner(System.in);
String className = in.nextLine();
//動態載入類
Class<?> clas = Class.forName(className);
//動態建立類對象
Object instance = clas.newInstance();
System.out.println(instance);
//動態檢查類中的公用成員方法資訊(包括超類和介面中的公用成員方法)
Method[] methods = clas.getMethods();
for (Method method : methods) {
System.out.println(method);
}
System.out.println("--------華麗分割線--------");
//動態檢查類中的所有方法資訊(包括私人和保護的,不包括繼承)
Method[] declaredMethods = clas.getDeclaredMethods();
for (Method method : declaredMethods) {
System.out.println(method);
}
String methodName = in.nextLine();
Method m = clas.getDeclaredMethod(methodName, null);
//動態執行方法
Object invoke = m.invoke(instance, null);//invoke是方法執行完畢後的傳回值
System.out.println(invoke);
}