java - 在反射中获取方法参数的类型
问题描述
我与反思一起工作。而我需要获取我的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.
解决方案
Method::getParameterTypes
返回Class[]
。
所以你的代码method.getParameterTypes().getClass()
总是会返回[Ljava.lang.Class
。试试这个代码:
Class[] types = method.getParameterTypes();
if (types.length == 1 && types[0] == String.class) {
// your second condition...
}
推荐阅读
- c# - C# 忽略 WCF 合同不匹配以实现向后兼容性?
- exception - Wildfly 11 向远程客户端抛出异常
- php - PHP - 无法将 PDF 文件及其文件名移动到目录路径
- firebase - Google Firebase Admin SDK 服务帐号已过期?
- android - Android Studio gradle 错误,方面
- android - 使用限制查询 Firebase 数据库
- google-apps-script - “错误 401(OAuth2 错误)!!1”运行 onInstall()
- python - ZODB python:如何避免创建只有一个大条目的数据库?
- sql - SQL 查询提供昨天中午 12:00 到晚上 11:59 之间的数据
- opencv - 用于从 equirectangular 图像估计 360 度摄像机位姿的 PNP