iSun
iSun

Reputation: 1754

Nested method invocation

I need to call a similar function like the below one in java through reflection:

MyPrivateClass.getDefault("test").hitCurrentSetting(true);

I thought that I can implement this like this but it's not working and throw me not cast exception:

    Class<?> c = Class.forName("com.xyz.MyPrivateClass"), instance = null;

    instance = (Class<?>) c.getMethod("getDefault", String.class).invoke(null, "test");

    Method method = instance.getMethod("hitCurrentSetting", boolean.class);
    method.invoke(null, true);

Any ideas on how to implement this?

Upvotes: 1

Views: 430

Answers (1)

Ian Rehwinkel
Ian Rehwinkel

Reputation: 2615

Try this:

Class<?> firstClass = Class.forName("com.xyz.MyPrivateClass");
Object firstCallResult = firstClass.getMethod("getDefault", String.class).invoke(null, "test");

Class<?> secondClass = firstCallResult.getClass();
Object secondCallResult = secondClass.getMethod("hitCurrentSetting", boolean.class).invoke(firstCallResult, true);

Upvotes: 2

Related Questions