I have the following class:
public abstract class A<T extends Event> {
void onEvent(T event);
}
and a Class<? extends Event> clazz
Class<? extends Event> clazz
object. How can I create an anonymous subclass of A
with the same generic type parameter as my class object? In other words, how can I get the type from my class object and pass it into a new subclass of A
?
Something like this:
new A<clazz.getType()>() {
@Override
public void onEvent(clazz.getType() event) {}
}
Java is a compiling language so you cannot dynamically change the class type so we have to define if blocks to change the type as per the data.
Your main Event
class:
public class Event {}
The A
class which get the type of class
public abstract class A<T extends Event> {
void onEvent(T t){};
}
Sample inherited class
public class Sample extends Event {}
Simple implementation
Sample sample = new Sample();
if (sample instanceof Sample) {
A<Sample> a = new A<Sample>() {
@Override
public void onEvent(Sample t) {
System.out.println(t.toString());
}
};
// Simple implementation
a.onEvent(sample);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.