本帖最后由 位丹丹 于 2012-10-6 16:10 编辑
- import java.beans.IntrospectionException;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- public class IntroSspectorTest {
- public static void main(String[] args) throws Exception {
- ReflectPoint pt1 = new ReflectPoint(3,6);
- String propertyName = "x";
- Object retVal = getProperty(pt1, propertyName);//此处抽取代码的作用和意义是什么?
- System.out.println(retVal);
- int value = 9 ;
- setProperty(pt1, propertyName, value);//还有此处
- System.out.println(pt1.getX());
- }
- private static void setProperty(Object pt1, String propertyName,
- int 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 pd1 = new PropertyDescriptor(propertyName,pt1.getClass() );
- Method methodGetX = pd1.getReadMethod();
- Object retVal = methodGetX.invoke(pt1);
- return retVal;
- }
- }
复制代码 代码抽取之后和不抽取运行结果一样,好像并没简化书写,那么抽取代码的意义是什么呢?望指点
|