3

我想创建一个包含静态方法(或包含对静态方法的引用)的数组。我试图创建一个类数组,这些类使用该方法实现接口。使用此方法,我将获取对象,然后在其上调用该方法。这不适用于静态方法。有没有办法在Java中做到这一点?

编辑:这是我迄今为止使用的方法:

interface TableElement{
    public Integer lookup(int value);
}

TableElement[] table = new TableElement[]
{
    new TableElement() { public Integer lookup(int value) { return 0; } },
    new TableElement() { public Integer lookup(int value) { return value * 3; } },
    new TableElement() { public Integer lookup(int value) { return value * value + 3; } },
};

public Integer find(int i, int value) {
    return table[i].lookup(value);
}

我希望 find 方法是静态的。

4

2 回答 2

3

当然,您可以拥有一个数组,Method然后您可以使用invoke 调用它,查看这些示例:如何使用反射(Java)调用私有静态方法?

于 2013-02-01T19:00:17.263 回答
0

如果你能满足以下条件:

  1. 您知道代码生成时的所有密钥。
  2. 您知道代码生成时的所有值(方法)。

你可以使用这样的代码:

public class Table {
    public static int hash(String key) {
        /* you can use any type of key and whatever hash function is
         * appropriate; this just meant as a simple example.
         */
        return key.length();
    }

    public static Integer find(String s, int value) {
        int h = hash(s);

        switch (h) {
          case 4: // "zero"
            if (s.equals("zero"))
                return methodZero(value);

          case 6: // "triple"
            if (s.equals("triple"))
                return methodTriple(value);

          case 11: // "squarePlus3"
            if (s.equals("squarePlus3"))
                return methodSquarePlus3(value);

          default:
            throw new UnsupportedOperationException(s);
        }
    }

    private static Integer methodZero(int value) { return 0; };
    private static Integer methodTriple(int value) { return value * 3; };
    private static Integer methodSquarePlus3(int value) { return value * value + 3; };

    /**
     * Just a demo.
     */
    public static void main(String arguments[]) {
        System.out.println("Zero(5): " + find("zero", 5));
        System.out.println("Triple(5): " + find("triple", 5));
        System.out.println("SquarePlus3(5): " + find("squarePlus3", 5));
        System.out.println("boom!");
        find("missingcode", 5);
    }
}

如果您需要放松任何一个要求,我不相信您可以静态地做所有事情。

如果您希望能够添加新键,则必须在添加时创建一个普通的哈希表来存储它们。(您可以在default代码中检查它。)

如果您希望能够替换值,则必须在此处使用间接级别,可能使用Method对象或实现Callable(您可以从方法体中调用它们methodZero)。

于 2013-02-01T23:41:28.560 回答