Reputation: 29
Need to call a private method foo()
of the class Inner.Private, where Private
is an inner private class from the main method of the main class.
The code is something like this:
public class MainClass {
public static void main(String[] args) throws Exception {
// Need to invoke foo() from here
}
static class Inner {
private class Private {
private String foo() {
return "someString";
}
}
}
}
I was trying to get this using Java Reflection, but I am facing issues from this approach.
My attempt to invoke the foo()
is:
Inner innerClassObject = new Inner();
Method method = Inner.Private.class.getDeclaredMethod("foo");
method.setAccessible(true);
method.invoke(innerClassObject);
But this gives a NoSuchMethodException:
Exception in thread "main" java.lang.NoSuchMethodException:
default.MainClass$Inner$Private.foo()
at java.lang.Class.getDeclaredMethod(Unknown Source)
I am stuck at this point, is this achievable by Java Reflection, or any other way?
Upvotes: 1
Views: 594
Reputation: 40024
Why waste an instantiation just to call a method as was described? You will inevitably want to save various instances for latter use as the classes develop.
public class MainClass {
public static void main(String[] args) throws Exception {
// Need to invoke foo() from here
Inner inner = new Inner();
Inner.Private pvt = inner.new Private();
System.out.println(pvt.foo());
}
static class Inner {
private class Private {
private String foo() {
return "someString";
}
}
}
}
Prints
someString
Upvotes: 0
Reputation: 868
Why are you doing this
Inner.Private.class
Instead of
innerClassObject.getClass()
For e.x:
public class Test {
private int foo(){
System.out.println("Test");
return 1;
}
public static void main(String [] args) throws InterruptedException,
NoSuchMethodException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException
{
Test innerClassObject = new Test();
Method method =
innerClassObject.getClass().getDeclaredMethod("foo",null);
method.setAccessible(true);
method.invoke(innerClassObject);
}
}
Upvotes: 0