gpt4 book ai didi

java - 假设我有构造函数,如何从类中调用方法?

转载 作者:行者123 更新时间:2023-12-04 14:46:52 24 4
gpt4 key购买 nike

如果我有一个构造函数对象 Constructor<?> productConstructor , 我怎样才能调用 run()该类中存在的方法?

例如,假设我有一个类:

public class product1{
public product1(Instances instance){
// constructor
}

public void run(){
// do something
}
}

我可以像这样为我的类运行构造函数:

Constructor<?> productConstructor;
productConstructor = getProductConstructor(instance.getProductName());
// pass instance into constructor to run the tests
// example of what is happening here -> new product1(instance)
productConstructor.newInstance(new Object[] { instance });
public Constructor<?> getProductConstructor(String productName) {
try {
logger.info("Looking for Product Class: {}", productName);
String fullQualifiedClassPath = "com.products." + productName;
Class<?> clazz = Class.forName(fullQualifiedClassPath);
return clazz.getConstructor(Instances.class);

} catch (Exception e) {
logger.error("Product: {} does not exist", productName);
}
return null;
}

如果我保持代码不变,那么我必须放置 run()构造函数内部的方法来运行它,但我想要 run()构造函数之外的方法。如何使用我的类的 Constructor 类调用我的 run 方法?

例如,像这样的东西是我想到的但不起作用:

Constructor<?> productConstructor;
productConstructor = getProductConstructor(instance.getProductName());
productConstructor.newInstance(new Object[] { instance }).run(); // added .run() to the end but this doesn't work.

这不起作用,因为 run未定义。这是因为我不能在一个直到运行时才知道的类上以这种方式调用方法。这就是我的问题所在。

最佳答案

问题是 productConstructor.newInstance(new Object[] { instance }); 检索了一个 Object 并且您必须将其转换为所需的类型 product1 :

((product1)productConstructor.newInstance(new Object[] { instance })).run();

让我向您提供我的一个项目reflection-utils .

<dependency>
<groupId>ru.oleg-cherednik.utils.reflection</groupId>
<artifactId>reflection-utils</artifactId>
<version>1.0</version>
</dependency>
product1 product1 = ConstructorUtils.invokeConstructor(product1.class, Instances.class, new Instances());
product1.run();

如果您不能包含该文件(例如文件具有包可见性),您可以使用名称来做同样的事情:

String className = "com.products.product1";
Object product1 = ConstructorUtils.invokeConstructor(className, Instance.class, new Instance());

String methodName = "run";
MethodUtils.invokeMethod(product1, methodName);

您可以在此处找到有关如何使用反射的更多示例。

关于java - 假设我有构造函数,如何从类中调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69866192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com