package com.what21.jdk15.demo06;
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.what21.jdk15.demo06;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class PropertyDescriptorDemo {
/**
* @throws Exception
*/
public static void invoke1() throws Exception{
Student student = new Student();
PropertyDescriptor pd = new PropertyDescriptor("id", Student.class);
// set调用
Method setMethod = pd.getWriteMethod();
setMethod.invoke(student, 10001);
// get调用
Method getMethod = pd.getReadMethod();
int returnValue = (int)getMethod.invoke(student, null);
// 调用结果
System.out.println(returnValue);
}
/**
* @throws Exception
*/
public static void invoke2() throws Exception{
Student student = new Student();
PropertyDescriptor pd = new PropertyDescriptor("name", Student.class);
// set调用
Method setMethod = pd.getWriteMethod();
setMethod.invoke(student, "我是学生");
// get调用
Method getMethod = pd.getReadMethod();
String returnValue = (String)getMethod.invoke(student, null);
// 调用结果
System.out.println(returnValue);
}
/**
* @param args
*/
public static void main(String[] args) {
try {
invoke1();
invoke2();
} catch (Exception e) {
e.printStackTrace();
}
}
}