public class Book {
private String name;
public String type;
public Book(){
}
public Book(String name,String type){
this.name = name;
this.type = type;
}
public String getName() {
System.out.println("通过反射,你调用了我的方法,得到了我的名字");
return name;
}
public void setName(String name) {
this.name = name;
System.out.println(this.name);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void showMoreType(String one,String two){
System.out.println("------------"+ one + "---------------"+ two);
}
}
public class MethodMain {
public static void main(String[] args) {
Book book = new Book();
book.setType("书本");
showMothod(book);
}
public static void showMothod(Object obj){
try {
Class cl = obj.getClass();//获得对象的类型
Field[] fields = cl.getDeclaredFields();//访问所有属性对象(公有和私有)
for (Field field : fields) {
System.out.println(field.getName());
}
Field[] f = cl.getFields();//只能访问公共属性对象
for (Field field : f) {
field.setAccessible(true);//要获得私有属性的值需要家该语句
System.out.println("属性名:" + field.getName() + "值:" + field.get(obj));//field.get(obj)获取属性值
System.out.println(field.getModifiers());//属性的权限修饰符
System.out.println(field.getType());//方法类型
}
Method method = cl.getMethod("getName", null);//获得方法名对象类型,参数为空,所以null
method.invoke(obj, new Object[0]);//对象,参数为空
Method m = cl.getMethod("setName", String.class);//获得setName的方法类型,参数为String类型
m.invoke(obj, "name");//对象,参数为“name”
//多参数 方法
Method method2 = cl.getMethod("showMoreType", new Class[]{String.class,String.class});
method2.invoke(obj, new Object[]{"肖","斌"});
} catch (Exception e) {
e.printStackTrace();
}
}
}