What are the interets of synthetic methods?

Posted by romaintaz on Stack Overflow See other posts from Stack Overflow or by romaintaz
Published on 2010-03-17T07:30:47Z Indexed on 2010/03/17 7:31 UTC
Read the original article Hit count: 174

Filed under:
|
|

Problem

One friend suggested an interesting problem. Given the following code:

public class OuterClass {

    private String message = "Hello World";

    private class InnerClass {
        private String getMessage() {
            return message;
        }
    }

}

From an external class, how may I print the message variable content? Of course, changing the accessibility of methods or fields is not allowed.

(the source here, but it is a french blog)


Solution

The code to solve this problem is the following:

try {
    Method m = OuterClass.class.getDeclaredMethod("access$000", OuterClass.class);
    OuterClass outerClass = new OuterClass();
    System.out.println(m.invoke(outerClass, outerClass));
} catch (Exception e) {
    e.printStackTrace();
}

Note that the access$000 method name is not really standard (even if this format is the one that is strongly recommanded), and some JVM will name this method access$0. Thus, a better solution is to check for synthetic methods:

Method method = null;
int i = 0;
while ((method == null) && (i < OuterClass.class.getDeclaredMethods().length)) {
    if (OuterClass.class.getDeclaredMethods()[i].isSynthetic()) {
        method = OuterClass.class.getDeclaredMethods()[i];
    }
    i++;
}
if (method != null) {
    try {
        System.out.println(method.invoke(null, new OuterClass()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

So the interesting point in this problem is to highlight the use of synthetic methods. With these methods, I can access a private field as it was done in the solution. Of course, I need to use reflection, and I think that the use of this kind of thing can be quite dangerous...

Question

What is the interest - for me, as a developer - of a synthetic method? What can be a good situation where using the synthetic can be useful?

© Stack Overflow or respective owner

Related posts about java

Related posts about synthetic-method