使用反射来定制超类的私有字段

时间:2016-05-19 13:03:12

标签: java

我遇到了一个问题,试图从子类中修改我的超类私有字段的行为(超类不是为了扩展而设计的,我无法改变它。)

基本上,我所拥有的是:

public class OrthoCanvas {
    private OrthoView xy, xz, zy;

    public class OrthoView { ... }
}

我想做那样的事情:

public class CustomOrthoCanvas extends OrthoCanvas {
    public CustomOrthoCanvas { 
        // Sets superclass xy, xz, zy to instances of CustomOrthoView
        // This seem to work fine (I'm using reflection to change the fields)
    }

    public class CustomOrthoView extends OrthoView { ... }
}

正如我所说,反射似乎有效(我正在构建CustomOrthoView)。但是,目前,我没有覆盖任何方法,我的构造函数只是超级(无论如何),还有一个Sysout来检查我在做什么。然而,OrthoView的原始行为刚刚消失,没有任何效果。

我的代码中是否犯了错误,或者这与我的具体案例有什么关系?

非常感谢

编辑:我只是觉得如果我向你展示我如何使用反射会更容易,所以它就是:

Field fieldXY = null;
Field fieldXZ = null;
Field fieldZY = null;
try {
    System.out.println(this.getClass().getSuperclass().getName());
    fieldXY = Class.forName(this.getClass().getSuperclass().getName()).getDeclaredField("xy");
    fieldXZ = Class.forName(this.getClass().getSuperclass().getName()).getDeclaredField("xz");
    fieldZY = Class.forName(this.getClass().getSuperclass().getName()).getDeclaredField("zy");
} catch (NoSuchFieldException e) {
    System.out.println("-- No such field --");
    System.out.println(e.getMessage());
} catch (SecurityException e) {
    System.out.println("-- Security failure --");
    System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
    System.out.println("-- Class not found --");
    System.out.println(e.getMessage());
}

fieldXY.setAccessible(true);
fieldXZ.setAccessible(true);
fieldZY.setAccessible(true);

try {
    fieldXY.set(this, new CustomOrthoView(this, DimensionId.Z));
    fieldXZ.set(this, new CustomOrthoView(this, DimensionId.Y));
    fieldZY.set(this, new CustomOrthoView(this, DimensionId.X));                
} catch (IllegalArgumentException e) {
    System.out.println("-- Illegal argument --");
    System.out.println(e.getMessage());
} catch (IllegalAccessException e) {
    System.out.println("-- Illegal access --");
    System.out.println(e.getMessage());
}

Edit2:这是超类的简化行为:

public class Orthoviewer {
    // This class creates a canvas to display an image

    public class OrthoCanvas {
        // This class represents how an image is displayed
        // It implements listeners (to navigate through the image for
        // example), and ways to refresh the image

        public class OrthoView extends JPanel {
           // This class displays one part of the image (one plane)
           // To represent a 3D point by the intersection of the three corresponding planes
           // It has an attribute which indicates its dimension 
           // (X is for ZY plane, Y for XZ plane etc)
           // It overrides the method paintComponent to draw itself

            public class ImageCache implements Runnable {
               // This handles the image to display on the corresponding plane
            }
        }
    }
}

0 个答案:

没有答案