Grofit
Grofit

Reputation: 18445

Can you reflect on a private static method in Java

First of all this is not some normal action I would want to do, however this fringe case involving alot of legacy code I cannot touch, and unit tests that need to be written for newer stuff.

Anyway I have a class and I can get access to all fields and methods through reflection, except private/protected static ones. So is there any way to get access to these private static method through reflection?

Upvotes: 3

Views: 1585

Answers (3)

Hayati Guvence
Hayati Guvence

Reputation: 728

Wrap those methods that can be accessed by an object. I believe that famous IDEs have already refactoring tools just for this purpose (class wrappers).

Upvotes: 0

Bozho
Bozho

Reputation: 597124

Method method = Foo.class.getDeclaredMethod("methodName");
method.setAccessible(true);
Object result = method.invoke(null);

Upvotes: 7

Boris Pavlović
Boris Pavlović

Reputation: 64632

Try powermock. It's a testing library that can do all kinds of stuff that you are supposed not to in greenfield development.

Upvotes: 0

Related Questions