我需要查找我当前的类是否有带有参数的方法,该参数的类型是 Integer,其泛型类型是 Integer。
我在main中写了以下内容:
public static main(String[] args){
Class<?> clazz = Class.forName("Test");
Class<?> lookingForClass = Integer.class;
Method[] method = clazz.getMethods();
for (int i = 0; i < method.length; i++) {
Type[] types = method[i].getGenericParameterTypes();
for (int j = 0; j < types.length; j++) {
Type type = types[j];
Class<?> result = type.getClass();
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Type[] fieldArgTypes = pt.getActualTypeArguments();
result = (Class<?>) fieldArgTypes[0];
}
if (result instanceof lookingForClass)
System.out.println("found it");
}
}
}
public static void findTowInArray(List<Integer> A) {
}
public static void findTowInArray(Integer A) {
}
public static void findTowInArray(String A) {
}
但是我在 if (result instanceoflookingForClass)
Incompatible conditional operand types Class<capture#6-of ?> and lookingForClass
出了什么问题?
最佳答案
如果 Type 已经是类,则不要对其调用 getClass()。
public static void main(String[] args) throws ClassNotFoundException{
Class<?> clazz = Class.forName("Test");
Class<?> lookingForClass = Integer.class;
Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
Type[] types = method.getGenericParameterTypes();
for (int j = 0; j < types.length; j++) {
Type type = types[j];
Class<?> result = type instanceof Class<?> ? (Class<?>)type : type.getClass();
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Type[] fieldArgTypes = pt.getActualTypeArguments();
result = (Class<?>) fieldArgTypes[0];
}
if (result.equals(lookingForClass))
System.out.println("found " + method);
}
}
}
我更喜欢像这样的循环
for (final Method method : methods) {
...
}
如果您不需要索引。
关于java - 查找方法参数类型或参数泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17021780/