Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...