将Class和Method作为参数传递

时间:2016-06-11 17:02:26

标签: java

我正在寻找一种将ClassMethod作为参数传递给方法的方法。我有重复的代码,我想减少。

我想要这样的事情:

public static void methodName(Class C, Method m ) {         
  C.m.sendKeys("item");                    
}

这可能吗?

2 个答案:

答案 0 :(得分:1)

在Java 8中,您可以使用作为lambda传递的方法引用;

methodName(C::m);

您需要指定函数的类型(参数和返回值),并使用现有的功能接口之一或定义自己的接口。

例如,如果您的函数返回一个布尔值并将类T的对象作为输入,则可以使用预定义的函数接口Predicate

public static void methodName(Item item, Predicate<Item> p) {
    p.test(item);
    // ...
}

答案 1 :(得分:0)

是的,您可以使用Consumer<...>。例如:

class MyClass {
    public static void methodToPass(String arg) {...}
}

public static void methodName(Consumer<String> cons) {
    cons.accept("item");
}

然后打电话给:

methodName(MyClass::methodToPass);

这也适用于实例方法,语法为:

MyClass mc = new MyClass();
methodName(mc::methodToPass);

或者,使用BiConsumer<...>,在这种情况下,传递的第一个参数必须是调用该方法的实例:

methodName(MyClass::methodToPass);
    
public static void methodName(BiConsumer<MyClass, String> cons) {
    MyClass mc = ...;
    cons.accept(mc, "item");
}

只要您调用的方法将您指定的类型的一个参数作为Consumer<...>的类型参数,就可以使用。

Consumer<...>包中还有其他可用的接口,如# The build number format is YYDDD.BB # YY is the last two digits of the year # DDD is the day number in the year (1-365) # BB is the build number of the day for this build type (1-N) # Get the build number from TeamCity. This will contain whatever is placed # into the build number portion of the build definition $TeamCityBuildNumber = "%build.number%" # Get the build counter from TeamCity and ensure it's in the format 00 (for sorting). # Assumption: there are less than 100 builds a day for this build definition. $TeamCityBuildCounter = "%build.counter%".PadLeft(2, "0") # The build number really just contains the date portion of the whole build number string. I am tweaking it to also contain a branch name but have removed this from my example code for simplicity purposes. $BuildNumber = ([string]::Concat(([DateTime]::Now.Date.Year - 2000),([DateTime]::Now.DayOfYear))) # Write the build number to the host, effectively altering the build number # within the process space of the build. Write-Host "##teamcity[buildNumber '$TeamCityBuildNumber.$BuildNumber.$TeamCityBuildCounter']" ,可用于不同类型的方法。