Java – checks at run time whether a class has a specific constructor that uses generics
•
Java
Hello:) I'm trying to choose the correct constructor in the class This is the code:
Constructor[] constructors = targetClass.getConstructors(); Constructor goodConstructor = null; for (Constructor constructor : constructors) { Class[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length = 1 && parameterTypes[0].equals(Map.class)) {//here goodConstructor = constructor; } }
I want to start from map Class switch to map < string, string > class. I vaguely remember that generics are only used at compile time, so that's why the compiler complains How do I check that the class has the correct constructor at run time?
Best wishes
Solution
You want to use getgenericparametertypes() instead of:
public class FindConstructor { public static void main(String[] args) throws IOException { for (Constructor<?> constructor : MyClass.class.getConstructors()) { Type[] parameterTypes = constructor.getGenericParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0] instanceof ParameterizedType) { ParameterizedType parameterizedArg = (ParameterizedType) parameterTypes[0]; if (parameterizedArg.getRawType() != Map.class) { continue; } if (parameterizedArg.getActualTypeArguments()[0] != String.class) { continue; } if (parameterizedArg.getActualTypeArguments()[1] != String.class) { continue; } } System.out.println("found constructor " + constructor); } } } class MyClass { public MyClass(Map<String,String> map) { } }
Now, if you change MyClass () to get map < string, integer > it will no longer match
It will be easier to use guava's typetoken, which uses anonymous classes to create parameterized types that we can compare
Type mapStringString = new TypeToken<Map<String,String>>(){}.getType(); for (Constructor<?> constructor : MyClass.class.getConstructors()) { Type[] parameterTypes = constructor.getGenericParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0].equals(mapStringString)) { System.out.println("found constructor " + constructor); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码