Reputation: 1754
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
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