Skip to content

Instantly share code, notes, and snippets.

@SiAust
Created December 9, 2020 10:11
Show Gist options
  • Save SiAust/33b1ef2b2101f6fcb14a28de30bf1360 to your computer and use it in GitHub Desktop.
Save SiAust/33b1ef2b2101f6fcb14a28de30bf1360 to your computer and use it in GitHub Desktop.
Java Reflection API example
// Do not remove imports
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.WildcardType;
import java.util.Set;
import java.util.Scanner;
class ListParameterInspector {
// Do not change the method
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
String methodName = scanner.next();
ListParameterInspector inspector = new ListParameterInspector();
inspector.printParameterType(new TestClass(), methodName);
}
public void printParameterType(TestClass obj, String methodName) throws Exception {
Method method = obj.getClass().getDeclaredMethod(methodName);
ParameterizedType param = (ParameterizedType) method.getGenericReturnType();
WildcardType wild = (WildcardType) param.getActualTypeArguments()[0];
System.out.println(wild.getUpperBounds()[0].getTypeName());
}
}
class TestClass {
public Set<? extends ClassB> someMethod() {
return Set.of(new ClassC(), new ClassB());
}
}
class ClassB {
}
class ClassC extends ClassB {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment