I have am getting a method, and checking method.getParameterTypes()[0]
, which is a java.util.List
. But I want to figure out what the containing type is, for instance if it's a java.util.List<String>
I want to figure out that it should hold strings.
How do I do this?
Thanks!
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
Type erasure is a process in which compiler replaces a generic parameter with actual class or bridge method. In type erasure, compiler ensures that no extra classes are created and there is no runtime overhead.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
Type listType = method.getGenericParameterTypes()[0];
if (listType instanceof ParameterizedType) {
Type elementType = ((ParameterizedType) listType).getActualTypeArguments()[0];
}
Note that the element type needn't be an actual Class
like String
-- it could be a type variable, a wildcarded type, etc.
You can read more about scraping generics info from reflected items here and here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With