在反射中获取方法参数的类型

时间:2018-09-04 10:59:37

标签: java reflection

我努力思考。而且我需要获取我的set()实体的参数方法以根据类型调用相应的fill方法。

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 ()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.

1 个答案:

答案 0 :(得分:1)

Method::getParameterTypes返回Class[]

因此,您的代码method.getParameterTypes().getClass()将始终返回[Ljava.lang.Class。尝试以下代码:

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