- 在这里做下记录,以便日后查看;
- 获得类的方法和成员变量:
public class ClassUtil {
/**
* 打印类方法
* @param o
*/
public static void printClassMethods(Object o){
Class clazz=o.getClass();
/**
* getDeclaredMethods()获得所有方法
* getMethods()获得public的方法
*/
Method[] methods=clazz.getDeclaredMethods();
for(Method method:methods){
Class returnType=method.getReturnType();
System.out.print(returnType.getName()+" ");
System.out.print(method.getName()+"(");
Class[] parameters=method.getParameterTypes();
for(Class class1:parameters){
System.out.print(class1.getName()+",");
}
System.out.println(")");
}
}
/**
* 打印类里面的成员变量
* @param o
*/
public static void printClassFields(Object o){
Class clazz=o.getClass();
Field[] fields=clazz.getDeclaredFields();
for(Field field:fields){
System.out.println(field.getType()+" "+field.getName());
}
}
public static void printClassConstructor(Object o){
Class clazz=o.getClass();
Constructor[] constructors=clazz.getConstructors();
for(Constructor constructor:constructors){
System.out.print(constructor.getName()+"(");
Class[] clazzs=constructor.getParameterTypes();
for(Class clazz1:clazzs){
System.out.print(clazz1.getName()+",");
}
System.out.println(")");
}
}
}
3、 调用类的方法:
public class Reflect2_invoke {
public static void main(String args[]){
A a1=new A();
try {
Class clazz=Class.forName("reflect.A");
Method method=clazz.getMethod("sayHello",new Class[]{String.class,String.class});
method.invoke(a1, new String[]{"tom","mary"});
} catch (Exception e) {
e.printStackTrace();
}
}
}
class A{
public String name="hi~";
public A() {
}
public void sayHello(String name1,String name2){
System.out.println("hello,"+name1+" and "+name2);
}
}