java在运行过程中,构建类,并获取方法集和属性集,构建实例并调用方法。
package com;
import java.lang.reflect.Method;
public class Test {
public static void main(String args[]) {
Class<?> c1 = null; // 声明Class对象c1
Person per = null;
try {
c1 = Class.forName("com.Person");
System.out.println(c1.getName() + " ");
Method m[] = c1.getMethods();
for (Method oo : m) {
System.out.print(oo.getName() + " ");
Class<?> r = oo.getReturnType();
System.out.print(r.getName() + " ");
Class<?> p[] = oo.getParameterTypes();
for (Class<?> o : p) {
System.out.print(o.getName() + " ");
}
System.out.println();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
try {
per = (Person) c1.newInstance();
per.speak();
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//运行结果
com.Person
speak void java.lang.String
speak void
wait void
wait void long int
wait void long
equals boolean java.lang.Object
toString java.lang.String
hashCode int
getClass java.lang.Class
notify void
notifyAll void
I am zhangsan age 20