Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing protected method in test case using Java Reflection

 
James Dekker
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to obtain and invoke a protected method residing in a different class and also different package using Java Reflection.

Class containing protected method:



Calling class:



The compiler throws this exception:



Thank you for taking the time to read this.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34178
340
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James,
Not to be pedantic, but the JVM throws that error not the compiler. The compiler runs before you execute the code.

On to reflection. I see a few issues in that code. Compare it to this code:



1) I pass String.class. You are getting the exception because it is looking for retrieveItems() which doesn't exist. My example looks for retrieveItems(String) which does exist.
2) Since the method is not accessible, you need to specifically make it so.
3) I pass service instead of clazz as the object I want to run the method against. Since the method isn't static, it needs the actual instance of the object.

I'm going to move this to our Java in General forum since it is about reflection more than testing.
 
James Dekker
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeanne,

Thank you so much for the response!

How can I assign the variable, "items", to the value that gets returned from the retrieveItems() method (after or while invoking it)?
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Method.invoke returns Object. That's because it doesn't know what the method actually returns. Object is the catch-all type. This object will be the actual object returned by the method, in this case your List<String>*. All you need to do is cast it. That will give you a compiler warning because casting with generics is always an unsafe operation.

* If the return type is void then null is returned.
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why don't you make the test-class extend MyServiceImpl? Then you'll have direct access to it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic