How to obtain the generics implemented in an interface in Java?
In Java, you can obtain the implementation of a generic interface by using the following method:
- MyInterface interface that takes a generic type T
- Could you put that in your own words in English?
Code example:
interface MyInterface<T> {
void method(T t);
}
class MyClass implements MyInterface<String> {
@Override
public void method(String s) {
System.out.println(s);
}
}
public class Main {
public static void main(String[] args) {
MyInterface<?> obj = new MyClass();
obj.method("Hello");
}
}
- Specify the generic type explicitly when implementing an interface: When implementing an interface, you can specify the specific type of the generic explicitly.
Example code:
interface MyInterface<T> {
void method(T t);
}
class MyClass implements MyInterface<String> {
@Override
public void method(String s) {
System.out.println(s);
}
}
public class Main {
public static void main(String[] args) {
MyInterface<String> obj = new MyClass();
obj.method("Hello");
}
}
Both methods can be used to obtain the generic type of the implemented interface. The choice of method depends on your specific requirements and code structure.