例1:
package Test1;
publicclass T {
static{
System.out.println("T类已经被加载");
}
publicvoid sayHello(){
System.out.println("T:你好");
}
publicvoid print(String str){
System.out.println(str);
}
}
package Test1;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
publicclass Test {
publicstaticvoid main(String[] args) {
String classPath="Test1.T"; //类路径和类名
try {
Class c=Class.forName(classPath); //将指定类加载到内存中
Object o=c.newInstance(); //创建对象
Method[] ms=c.getMethods(); //获得该类全部方法,和从继承父类的方法
Class[] ptys; //方法参数类型
for(Method m:ms){
if(m.getName().equals("print")){ //如果是print方法
ptys=m.getParameterTypes(); //获得该方法的全部参数类型
for(Class tmp:ptys){
System.out.println(tmp); //输出print方法的全部参数类型
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
输出:
T类已经被加载
class java.lang.String