Created
December 9, 2020 10:11
-
-
Save SiAust/33b1ef2b2101f6fcb14a28de30bf1360 to your computer and use it in GitHub Desktop.
Java Reflection API example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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