public class IntroSpectorDemo {
public static void main(String[] args) throws Exception {
ReflectPoint2 pt1 = new ReflectPoint2(3,5);
String propertyName="x";
//"x"-->"X"-->"getX"-->"MethodGetX"-->
PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodGetX = pd.getReadMethod();
Object retVal = methodGetX.invoke(pt1);
System.out.println(retVal);
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodSetX = pd2.getWriteMethod();
methodSetX.invoke(pt1, 7);
//选中pt1.getX(),ALT+/可以自动填上输出语句
System.out.println(pt1.getX());;
}
现在想把标绿色的部分抽取成方法:
第一步,选中这三行,点右键-->Refactor-->Extract Methos-->
在Method name文本框里填上方法名就会自动生成方法了。如填上”getProperty“,点击OK后,代码就编程这样了:
public class IntroSpectorDemo {
public static void main(String[] args) throws Exception {
ReflectPoint2 pt1 = new ReflectPoint2(3,5);
String propertyName="x";
//"x"-->"X"-->"getX"-->"MethodGetX"-->
Object retVal = getProperty(pt1, propertyName);
System.out.println(retVal);
Object value = 7;
setProperties(pt1, propertyName, value);
//选中pt1.getX(),ALT+/可以自动填上输出语句
System.out.println(pt1.getX());;
}
private static void setProperties(Object pt1, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodSetX = pd2.getWriteMethod();
methodSetX.invoke(pt1, value);
}
private static Object getProperty(Object pt1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodGetX = pd.getReadMethod();
Object retVal = methodGetX.invoke(pt1);
return retVal;
}
}
setProperties()方法生成步骤类似,只是要注意一点:
methodSetX.invoke(pt1, 7);方法不会识别7这个常量,为了使方法能将7生成一个参数,需要建立一个变量,值设为7,把这个变量传给invoke()才行。