您的位置:首页 > 编程语言 > Java开发

利用myeclipse的重构自动抽取成方法

2013-06-06 11:03 176 查看
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()才行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐