英文:
How pass methods as parameters in Java using method reference notation (Class::method)?
问题
我想在一个 Utils
类中创建一个方法,该方法接受两个参数,第一个参数是领域类(domain class),第二个参数是领域类中的一个方法(以引用的方式传递)。这个 Utils
类有一个方法,将在领域类实例的范围内创建一个类实例,并执行这个方法。
例如,领域类:
public class DomainClass {
public void dummyMethod() {}
}
Utils 类:
public class Utils {
public static void execute(Class<?> clazz, Runnable referenceMethod) {
Object objInstance = clazz.getConstructor().newInstance();
// 在 objInstance 的范围内执行 referenceMethod
}
}
我想要的调用类似于:Utils.execute(DomainClass.class, DomainClass::dummyMethod)
。然而,这个场景存在一些问题:
- 我该如何为
Utils
类传递这些参数(我现在遇到了一些编译问题)? - 我该如何在
objInstance
的范围内调用referenceMethod
?
英文:
I want to create method in a Utils
class that accepts two parameters, the first is the domain class, and the second is a method from the domain class (passed as reference). This Utils
' class has a method that will create an instance of the class and execute the method in the scope of the domain class instance.
For example, the domain class:
public class DomainClass {
public void dummyMethod() {}
}
The Utils class:
public class Utils {
public static void execute(Class<?> clazz, Runnable referenceMethod) {
Object objInstance = clazz.getConstructor().newInstance();
// execute the 'referenceMethod' on the scope of 'objInstance'
}
}
The call I want is something like: Utils.execute(DomainClass.class, DomainClass::dummyMethod)
. However, this scenario has some problems:
- How can I pass this parameters for the
Utils
class (now I'm having some compilation problems)? - How can I call the 'referenceMethod' with the scope of 'objInstance'?
答案1
得分: 7
DomainClass::dummyMethod
是对一个实例方法的引用,你需要提供一个对象实例来运行它。这意味着它不能是一个Runnable
,但可以是一个Consumer
,例如。
另外,将execute
方法改造为泛型会很有帮助:
public static <T> void execute(Class<T> clazz, Consumer<T> referenceMethod) {
try {
T objInstance = clazz.getConstructor().newInstance();
referenceMethod.accept(objInstance);
} catch (Exception e) {
e.printStackTrace();
}
}
现在你可以像这样调用execute
方法:
Utils.execute(DomainClass.class, DomainClass::dummyMethod);
英文:
DomainClass::dummyMethod
is a reference to an instance method, and you need to provide an object instance to run it. This means it cannot be a Runnable
, but it can be a Consumer
for example.
Also, it will help to make the execute
method generic:
public static <T> void execute(Class<T> clazz, Consumer<T> referenceMethod) {
try {
T objInstance = clazz.getConstructor().newInstance();
referenceMethod.accept(objInstance);
} catch (Exception e) {
e.printStackTrace();
}
}
Now you can call execute
like this:
Utils.execute(DomainClass.class, DomainClass::dummyMethod);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论