Skip to content
Advertisement

How to check if the type is instanceof an interface in java?

I have a class (CreateAccountRequest) that implement an interface(Iloggable), the interface has no method, Just for marking purpose.

JavaScript

In my custom RequestBodyAdviceAdapter class, trying to check if the request is an instance of Iloggable, to proceed or ignore the request (for instance do the logging or not )

I know we can use instanceOf operator to check if an object implements an interface or not and the unit test as below approve it:

JavaScript

But in RequestBodyAdviceAdapter supports method the result is false or true all the time, I tried different ways to distinguish if the parameter implement the interface or not

JavaScript

For removing any doubt, I put a snapshot of the debugging in the support method:

enter image description here

Advertisement

Answer

In this case type is a java.lang.reflect.Type (instance) and not an CreateAccountRequest (instance;)

You could get more lucky with:

JavaScript

Class.isAssignableFrom(...)-javadoc-17

Type -> Class

In depth:

  • JavaScript
  • JavaScript
  • JavaScript

But I assume (when correctly used -> experiment) some MethodParameter methods should also lead to the desired. Especially:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement