首页 > 解决方案 > 在反射中获取方法参数的类型

问题描述

我与反思一起工作。而我需要获取我的set()实体的参数方法,根据类型调用对应的填充方法。

try{
            Class clazz = aClass.getClass();
            Object object = clazz.newInstance();
            while (clazz != Object.class){
                Method[] methods = clazz.getDeclaredMethods();
                for (Method method : methods){
                    if (method.isAnnotationPresent(ProductAnnotation.class)) {
                        Object[] strategyObj =  new Object[1];
                        if (method.getReturnType().getName().equals("int")) {              //reflexion never comes in if
                            strategyObj[0] = strategy.setInt(bundle.getString(method.getName().substring(3).toLowerCase()));
                            method.invoke(object, strategyObj);
                        }if (method.getParameterTypes().getClass().getTypeName().equals("String")){   //reflexion never comes in if
                            strategyObj[0] = strategy.setString(bundle.getString(method.getName().substring(3).toLowerCase()));
                            method.invoke(object, strategyObj);
                        }
                    }
                }
                clazz = clazz.getSuperclass();
            }
            return (FlyingMachine) object;
        } catch (IllegalAccessException | IOException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

我尝试使用getReturnedType ()and getParametrTypes (),但反射没有进入任何条件。我做错了什么?

我的注释

@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface ProductAnnotation {
    String value();
}

应该引起反射的方法。根据方法的类型,调用这些方法之一进行进一步处理和填充数据。

@Override
    public int setInt(String title) throws IOException {
        String line = null;
        checkValue = true;
        while (checkValue) {
            System.out.println(title + "-->");
            line = reader.readLine();
            if (line.matches("\\d*")) {
                System.out.println(title + " = " + Integer.parseInt(line));
                checkValue = false;
            } else {
                System.out.println("Wrong value, try again");
                checkValue = true;
            }
        }
        return Integer.parseInt(line);
    }

setString() works exactly the same scheme.

标签: javareflection

解决方案


Method::getParameterTypes返回Class[]

所以你的代码method.getParameterTypes().getClass()总是会返回[Ljava.lang.Class。试试这个代码:

Class[] types = method.getParameterTypes();
if (types.length == 1 && types[0] == String.class) {
    // your second condition...
}

推荐阅读