Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get List<Type> with reflection?

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!

like image 637
Rocky Pulley Avatar asked Jan 18 '13 15:01

Rocky Pulley


People also ask

What is Java reflection?

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.

What is type erasure in Java?

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.

What are generics in Java?

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.


1 Answers

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.

like image 159
pholser Avatar answered Sep 30 '22 19:09

pholser