views:

58

answers:

5

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.

+4  A: 

You can't. The whole point of it being private is that you can't get at the variable. If the class hasn't given any way of finding it out, you can't get it. That may or may not be a design flaw in the class, but unless you use reflection with suitable privileges (which I don't recommend - you're basically relying on private implementation details) you're going to have to think of an alternative approach.

Jon Skeet
A: 

You can't access private variables from outside of the class. In order to access it you would have to have it be protected.

dave
+2  A: 

You could use reflection but it's a bad idea. A private field is private because the developer doesn't want you to mess with it.

I won't give you the way to do it here, but if you really know what you do, follow the links below at your own risks. Again, you shouldn't even think about doing this.


On the same topic :

Colin Hebert
A: 

You can do this with the Reflection API (Specifically, see the setAccessible() method). Anyway, this is a hack and may not work if there is a SecurityManager installed in the VM.

gpeche
+1  A: 

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 - incapsulation.

But sometimes programmer 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.

Vadeg