MattHicks.com

Programming on the Edge

Some Rules Can't Be Broken

Published by Matt Hicks under , , on Wednesday, May 28, 2008
I'm a big lover of Reflection in Java. It's extremely powerful and lets you do things that technically shouldn't be allowed. For example, an Object with a private method cannot be invoked outside of that method by virtue of the "private" keyword. However, if you use reflection:

public class MyObject {
private void doSomethingHidden() {
System.out.println("I'm hidden and can't be invoked!");
}
}


public class Test {
public static void main(String[] args) throws Exception {
MyObject o = new MyObject();

Method method = MyObject.class.getDeclaredMethod("doSomethingHidden");
method.setAccessible(true);
method.invoke(b, new Object[0]);
}
}


You can invoke the method by setting accessible to true.

I was attempting to do a similar breaking of rules to try to invoke the underlying method of an overridden class:

public class ObjectA {
public void doSomething() {
System.out.println("I'm ObjectA!");
}
}


public class ObjectB extends ObjectA {
public void doSomething() {
System.out.println("I'm ObjectB! Yay!");
}
}


import java.lang.reflect.Method;

public class Test {
public static void main(String[] args) throws Exception {
ObjectB b = new ObjectB();
b.doSomething();

Method method = ObjectA.class.getDeclaredMethod("doSomething");
method.invoke(b, new Object[0]);
}
}


Unfortunately this always invokes the overridden implementation instead. It's a shame the only way to do this is via super.doSomething() from within the overriding Class. Oh well, I guess it's best that you can't do it as it would be a blatant violation of the intentions of Object overriding.

0 comments:

Post a Comment