suat
suat

Reputation: 4289

Invoking a private method having a Class<T> typed parameter via reflection

I have a method as follows:

private <T> T _findEntity(Class<T> klass, Object entityId) {
    ...
}

To invoke this function via reflection, I have tried the below snippet with an unsuccessful result:

Method method = GenericPersistenceManager.class.getDeclaredMethod("_findEntity", Object.class, Object.class);
method.setAccessible(true);
Player player = (Player) method.invoke(genericPersistenceManager, Player.class, "str");

So is there a way to call a method like _findEntity via Java reflection?

Thanks

Upvotes: 0

Views: 878

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213351

You are searching for wrong method. Your method takes two arguments of type - Class and Object. And you are searching for method which takes Object as both the arguments.

You should change your 2nd argument to Class.class:

Method method = GenericPersistenceManager.class.getDeclaredMethod("_findEntity", 
                                                     Class.class, Object.class);

Upvotes: 3

AlexR
AlexR

Reputation: 115388

Change your call to

Method method = GenericPersistenceManager.class.getDeclaredMethod("_findEntity", Class.class, Object.class);

Upvotes: 1

Related Questions