Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing nested private static class in Java

I have following public class in Java which looks like:

public class MyClass 
{

  private static class MyNestedClass<T> extends SomeOtherClass
  {
  }

}

I am writing a test where I need to create a mock object for MyNestedClass class using PowerMockito, but am not able to access the class since it's private. Is there a way I can access MyNestedClass?

I tried the following:

MyClass.MyNestedClass myNestedClass = new MyClass.MyNestedClass()

and

MyClass testNoteActivity = Mockito.spy(MyClass.class);
testNoteActivity.MyNestedClass myNestedClass = new testNoteActivity.MyNestedClass()

Both didn't work for me.

like image 444
tech_human Avatar asked Jun 07 '26 14:06

tech_human


1 Answers

You can access private classes via reflection:

final Class<?> nestedClass = Class.forName("MyClass$MyNestedClass");
final Constructor<?> ctor = nestedClass.getDeclaredConstructors()[0];
ctor.setAccessible(true);
final Object instance = ctor.newInstance();
System.out.println(instance);

but it's not very good practice.

To find class with Class.forName you should provide full class name including package. E.g. if MyClass located in com.test package this string should be "com.test.MyClass$MyNestedClass".

like image 151
Kirill Avatar answered Jun 09 '26 04:06

Kirill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!