简体   繁体   English

在Java中,可以将一行代码作为方法参数?

[英]In Java, it is possible to take a line of code as a method argument?

I can't seem to find anything on google for this and I'm not sure it's possible. 我似乎无法在谷歌上找到任何东西,我不确定它是否可能。 What I want to do, is pass a line of Java code as an argument to a method. 我想要做的是将一行Java代码作为参数传递给方法。 Google only turns up results for passing cmd line arguments to methods, but I want to pass an actual line of code. Google只会将cmd行参数传递给方法,但我希望传递一行实际的代码。

Basically I want to pass methodA to methodB except methodA isn't a method, but a line of code. 基本上我想将methodA传递给methodB,除了methodA不是方法,而是一行代码。 Below is a full example of passing a method to a method using reflection. 下面是将方法传递给使用反射的方法的完整示例。

public class Relation<T> {

protected Set<Pair<T,T>> pairs = null;

public Relation() {
    this.pairs = new LinkedHashSet<Pair<T,T>>();
}

    /* Next 2 methods are methods for sending methods to methods useing java.lang.reflect.Method */
    public Method getMethod(String name) {
        try {   return Relation.class.getDeclaredMethod(name);
        } catch (Exception e) {} 
        return null;
    }

    public boolean execute(Method method, Object... params) {
        try {   return (Boolean) method.invoke(this, params);
        } catch (Exception e) {}
        return false;
    }

    /* The method I reuse several times so I just put methods inside of it */   
    public boolean pairsTFIterator(Method method)  {
        for(Pair<T,T> x : pairs) {
            boolean bool = false;
            for(Pair<T,T> y : pairs) {
                if(execute(method, x,y))    
                    bool = true; break;
            }
            if(!bool) return false;
        }
        return true;
    }

    /* To be replaced by the line of code*/   
    public static <T> boolean isSymmetricPairs(Pair<T,T> a, Pair<T,T> b) {
        return a.getFirst().equals(b.getSecond()) && a.getSecond().equals(b.getFirst()) ? true :false;
    }

    /* Method that calls others */
    public boolean isSymmetric() {
        return pairsTFIterator(getMethod("isSymmetricPairs"));
    }
}

The above works fine and all, but I want to take it a step further and just forego methods like the "isSymmetricPairs" method by just putting that methods logic line directly in the "pairsTFIterator", like so: 以上工作正常,但是我想更进一步,只是放弃像“isSymmetricPairs”方法这样的方法,只需将那些方法逻辑行直接放在“pairsTFIterator”中,就像这样:

public boolean isReflexive() {  
    return  baseSetTFIterator(
            a.getFirst().equals(b.getSecond()) && a.getSecond().equals(b.getFirst()) ? true :false
    );
}

I'm pretty sure this is impossible, but if there is someway to do it, that would be great. 我很确定这是不可能的,但如果有办法做到这一点,那就太好了。

It sounds like what you are looking for are "first-class functions". 听起来你正在寻找的是“一流的功能”。 Some languages treat functions just like a variable, in the sense that you can assign them to variables and pass them as arguments to other functions. 有些语言将函数看作变量,因为您可以将它们分配给变量并将它们作为参数传递给其他函数。 Java 8 will be introducing the concept of lambda expressions which will support this type of functionality. Java 8将引入lambda表达式的概念,它将支持这种类型的功能。

Also there are other JVM languages that provide this already, including Scala and Groovy to name two of the more popular ones. 还有其他JVM语言已经提供了这一点,包括Scala和Groovy,以命名两个更受欢迎的语言。

Just to give you a flavor of what it looks like, in Groovy you can execute arbitrary functions on each element of a collection by calling the each() method and passing it a closure (a function essentially). 只是为了让你了解它的样子,在Groovy中你可以通过调用each()方法并向它传递一个闭包(本质上是一个函数)来对集合的每个元素执行任意函数。

def list = [1, 2, 3, 4]
def printer = { x -> println x } // defines a closure that takes one arg and prints it
list.each(printer) // prints out the elements

def sum = 0
def summer = { x -> sum += x } // defines a closure that takes one arg and adds it to the sum variable
list.each(summer)
println sum // should be 1 + 2 + 3 + 4

Put you code in an anonymos inner class may satisfy your requirement: 将代码放入anonymos内部类可满足您的要求:

    interface PairFilter<T>{
        boolean filter(Pair<T, T> a, Pair<T,T> b);
    }

And in you iterator method: 在你的迭代器方法:

    public boolean pairsTFIterator(PairFilter filter) {
        for(Pair<T,T> x : pairs) {
            boolean bool = false;
            for(Pair<T,T> y : pairs) {
                if(filter.filter(x,y))    
                    bool = true; break;
                }
                if(!bool) return false;
        }
        return true;
    }

then call it: 然后叫它:

    pairsTFIterator(new PairFilter<T>(){
        public boolean filter(Pair<T, T> a, Pair<T,T> b){
            return a.getFirst().equals(b.getSecond()) && a.getSecond().equals(b.getFirst()) ? true :false;
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中是否可以定义一个通用方法来将超类型类作为参数? - In Java is it possible to define a generic method to take a supertype class as an argument? Java 8 中的注解中取方法参数作为参数 - Take method argument as an argument in the annotation in Java 8 toString()方法可以在Java中接受参数吗? - Can toString() method take an argument in Java? 我是否可以使用可以将HashMap或列表作为参数的方法? - Is it possible for me to have a method that can take both a HashMap or a list as an argument? 我如何在java中将char作为命令行参数 - how can i take in a char as an command line argument in java 是否可以在Java中使用默认值定义方法参数? - Is it possible to define method argument with default values in Java? Java如何将字符作为参数,然后该方法前后打印顺序? - Java how to take chars as an argument and then the method prints the sequence forwards and backwards? Java方法如何接受扩展通用类型的参数 - How can a java method take an argument that extends a generic type 为什么scalac采用Java vararg方法而不是单个参数 - Why does scalac take the Java vararg method instead of the single argument 将命令行 unicode 参数传递给 Java 代码 - Passing command line unicode argument to Java code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM