Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

inheritance - Access a private variable of the super() class in Java - JChart2D

I have extended a class in Java that has a private variable that I want to get the value of before it is changed. There are no methods to access this variable in the super class. I have tried super().m_zoomArea (the variable is in the ZoomableChart class of jChart2D). The variable is updated when the mouseDragged method is called. I have overridden this method and would like to get the value of the variable before it is updated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can access private variable of any class, but it's a bad idea, because you're breaking one of the basic principles of OOP - encapsulation.

But sometimes programmer are forced to break it. Here is the code, which solves your problem:

Extended class

public class ExtZoomableChart
extends ZoomableChart {

public Rectangle2D getZoomArea() {
    try {
        Field field = ZoomableChart.class.getDeclaredField("m_zoomArea");
        field.setAccessible(true);
        Object value = field.get(this);
        field.setAccessible(false);

        if (value == null) {
            return null;
        } else if (Rectangle2D.class.isAssignableFrom(value.getClass())) {
            return (Rectangle2D) value;
        }
        throw new RuntimeException("Wrong value");
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

}

}

and call example:

public class Main {
    public static void main(String[] args) {
        ExtZoomableChart extZoomableChart = new ExtZoomableChart();

        Rectangle2D d = extZoomableChart.getZoomArea();
        System.out.println(d);
    }
}

You don't need to extend ZoomableChart to get private variable. You can get it value almost from everywhere. But remember - usually it's a bad practice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...