[英]Java: Passing classname to function
I have three very similar functions and want to refactor. 我有三个非常相似的功能,想重构。 However, the functions use a function from a class, thus, I wonder if there is a way to pass the class / class name to the function?
但是,这些函数使用类中的函数,因此,我想知道是否存在将类/类名传递给函数的方法吗?
new GenericClass1 = genericClass1;
new GenericClass2 = genericClass2;
new GenericClass3 = genericClass3;
public ReturnsClass1 myFunction1 (){
return genericClass1.functionFromClass(paramter);
}
public ReturnsClass2 myFunction2 (){
return genericClass2.functionFromClass(paramter);
}
public ReturnsClass3 myFunction3 (){
return genericClass3.functionFromClass(paramter);
}
To illustrate I would like something like this: 为了说明我想要这样的事情:
public ReturnsClass myFunction (classInstance) {
return classInstance.functionFromClass(parameter);
}
You can make GenericClass*
implement a common generic interface, in which the method returns an instance of the generic type parameter. 您可以使
GenericClass*
实现通用的通用接口,该方法在该接口中返回通用类型参数的实例。
interface GenericInterface<T> {
T functionName(Object parameter); //change parameter type
}
This can then be extended by GenericClass*
: 然后可以通过
GenericClass*
对其进行扩展:
class GenericClass1 implements GenericInterface<ReturnsClass1> {
public ReturnsClass1 functionName(Object parameter) {
...
}
}
In the same manner, GenericClass2
will implement GenericInterface<ReturnsClass2>
and GenericClass3
will implement GenericInterface<ReturnsClass3>
. 以相同的方式,
GenericClass2
将实现GenericInterface<ReturnsClass2>
而GenericClass3
将实现GenericInterface<ReturnsClass3>
。
Your method will then look like this: 您的方法将如下所示:
public <T> T myFunction (GenericInterface<T> classInstance) {
return classInstance.functionName(parameter);
}
You could try using java.util.function.Function<T, R>
. 您可以尝试使用
java.util.function.Function<T, R>
。
It may look like this: 它可能看起来像这样:
public <R> R myFunction (Function<Object, R> func) {
return func.apply(parameter);
}
Usage: 用法:
ReturnClass1 rc1 = myFunction(genericClass1::functionFromClass);
ReturnClass2 rc2 = myFunction(genericClass2::functionFromClass);
The pros of this approach is that you don't need your generic classes to share an interface and all refactoring goes into myFunction
. 这种方法的优点是,您不需要通用类来共享接口,所有重构都将放在
myFunction
。 This interface is a functional interface that was introduced in Java 8, you can read more about it in the docs . 该接口是Java 8中引入的功能性接口,您可以在docs中阅读有关该接口的更多信息。 Simply what it does, it defines a function that accept a single agrument of type
T
and returns a value of type R
. 它的作用很简单,它定义了一个函数,该函数接受类型
T
一个单数,并返回类型R
的值。
And the wierd looking ::
is a method reference 而看起来
::
的怪异方法参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.