[英]Want to pass class.getmethod arguments dynamically in run time java
I want to invoke a method from by giving methodName in runtime. 我想通过在运行时提供methodName来调用方法。 I can do it in below way.
我可以按照以下方式来做。
Method method = MyObject.class.getMethod("doSomething", String.class);
Object returnValue = method.invoke(null, "parameter-value1");
But I want to list down all the overloaded methods with that method name and the different set of arguments and let the user choose a particular overloaded method and dynamically pass those arguments in 但是我想列出所有带有该方法名称和不同参数集的重载方法,并让用户选择一个特定的重载方法并在其中动态传递这些参数。
Method method = MyObject.class.getMethod("doSomething", String.class);
instead of hardcoding String.class
. 而不是对
String.class
进行硬编码。
suppose I have two methods like 假设我有两种方法
methodName(String)
and overloaded method 和重载方法
methodName(String, int)
I want to let the user choose which one to pick in runtime and pass that information for getMethod
function for that particular method. 我想让用户选择在运行时中选择哪个,并将该信息传递给该特定方法的
getMethod
函数。
How can I do this? 我怎样才能做到这一点?
We have a method called Class.forName(String)
to load an instance of Class<?>
by its name. 我们有一个称为
Class.forName(String)
的方法,用于通过其名称加载Class<?>
的实例。
The problem is that we have to pass the fully qualified name of the desired class (including the name of a package). 问题是我们必须传递所需类的全限定名(包括包名)。 It means that
Class.forName("String")
is not going to work. 这意味着
Class.forName("String")
将无法正常工作。 Instead, we need to call it as Class.forName("java.lang.String")
. 相反,我们需要将其称为
Class.forName("java.lang.String")
。
We could have a map (or enum) to keep those Class<?>
es. 我们可以有一个映射(或枚举)来保留这些
Class<?>
es。 Since we are expecting the user to collaborate, keys would be String
s and the structure would be like Map<String, Class<?>>
: 由于我们期望用户进行协作,因此键将为
String
,结构将类似于Map<String, Class<?>>
:
user > string
we < class java.util.String
Then, we should figure out how to parse method arguments according to their types - they are going to come as String
s. 然后,我们应该弄清楚如何根据它们的类型解析方法参数-它们将作为
String
。 I would utilise a Function<String, ?>
per type: 我会使用每个类型的
Function<String, ?>
:
Function<String, T> converter = (String s) -> T.convertFromString(s);
To make it more clear for you, I wrote a simple, complete example for you: 为了使您更清楚,我为您编写了一个简单而完整的示例:
class Test {
// prints s once
public static void method(String s) {
System.out.println(s);
}
// prints s i times
public static void method(String s, int i) {
System.out.println(IntStream.rangeClosed(0, i - 1)
.mapToObj($ -> s)
.collect(Collectors.joining(" ")));
}
public static void main(String[] args) {
perform();
}
public static Object perform() {
final Scanner scanner = new Scanner(System.in);
// read the method name
final String methodName = scanner.nextLine();
final Method[] methods = Arrays.stream(Test.class.getDeclaredMethods())
.filter(m -> m.getName().endsWith(methodName) && !m.isSynthetic())
.toArray(Method[]::new);
// read the method parameter types in the format "type1 type2"
final String rawMethodParametersTypes = scanner.nextLine();
final SupportedType[] methodParameterTypes = Arrays.stream(rawMethodParametersTypes.split(" "))
.map(p -> SupportedType.valueOf(p.toUpperCase()))
.toArray(SupportedType[]::new);
final Optional<Method> selectedMethod = Arrays.stream(methods)
.filter(m -> Arrays.equals(Arrays.stream(methodParameterTypes)
.map(SupportedType::getType).toArray(Class<?>[]::new), m.getParameterTypes()))
.findAny();
if (!selectedMethod.isPresent()) {
return null;
}
final Method method = selectedMethod.get();
// read method arguments in the format "arg1 arg2"
final String rawMethodArgumentsLine = scanner.nextLine();
final String[] rawMethodArguments = rawMethodArgumentsLine.split(" ");
final int expectedLength = method.getParameterCount();
if (rawMethodArguments.length != expectedLength) {
return null;
}
Object[] methodArguments = new Object[expectedLength];
for (int i = 0; i < expectedLength; ++i) {
methodArguments[i] = methodParameterTypes[i].getConverter().apply(rawMethodArguments[i]);
}
try {
return method.invoke(null, methodArguments);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
I introduced an enum SupportedType
to declare the types we are going to support and which the user might encounter with while choosing the signature. 我引入了一个枚举
SupportedType
来声明我们将要支持的类型以及用户在选择签名时可能遇到的类型。
@RequiredArgsConstructor
public enum SupportedType {
STRING(String.class, s -> s),
INT(int.class, Integer::valueOf);
@Getter
private final Class<?> type;
@Getter
private final Function<String, Object> converter;
}
Here are input-output examples for method(String, int)
这是
method(String, int)
输入输出示例
> method
> string int
> hello 5
< hello hello hello hello hello
and method(String)
和
method(String)
> method
> string
> hello
< hello
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.