-1

TLDR: I need a method to get the being implemented as an interface in a class using reflection. (read the last line too, please...)

The problem is simple, but I can't solve it, I have an interface EventListener, with the following code:


public @IndexSubclasses interface EventListener<T> {
    public void onEvent(T event);
}

And I have an implementation, the JoinEventSampleBase (which is only a sample to be copied), with the following code:

@Scope.Server @FrameworkEvent
public class JoinEventBaseSample implements EventListener<JoinEvent> {
    @Override
    public void onEvent(JoinEvent event) {
        // Code here
    }
}

I had tried the following on my EventManager:

 Class<?> eventIndication = Arrays.stream(listener.getInterfaces())
       .filter(aClass -> aClass.getName().equals(EventListener.class.getName()))
 .findFirst().get().getComponentType();

It is confuse because it was only a test.

I got the following error:

java.lang.NullPointerException: Cannot invoke "java.lang.Class.getDeclaredField(java.lang.String)" because "eventIndication" is null

The line that is doing the error after the "eventIndication" var is the following:

Object instance = eventIndication.getDeclaredField("instance").get(null);

Finally, my objective is access the instance method into the eventIndication field which is into the JoinEvent class in

implements EventListener<JoinEvent>
  • 1
    Did you read the Javadoc for `getComponentType`? What are you expecting it to return? – tgdavies Jan 29 '22 at 04:19
  • You might want to check other questions like https://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection, https://stackoverflow.com/questions/1942644/get-generic-type-of-java-util-list or https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime – Progman Jan 29 '22 at 11:13
  • I readed it but I didn't see that this only works in array. Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null. – Plugner Jan 29 '22 at 12:42

1 Answers1

0

It works, thanks (:

My code:


ParameterizedType parameterizedType = (ParameterizedType) listener.getGenericInterfaces()[0];
Class<?> eventIndication = (Class<?>) parameterizedType.getActualTypeArguments()[0];