gpt4 book ai didi

java - 是否可以静态地反射(reflect)一个java方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:25:12 26 4
gpt4 key购买 nike

有没有办法在 Java 中静态引用反射方法。下面是一些示例代码,可让您了解我正在尝试的内容:

public void myFunc(int x) { ... }

public void other() {
Method m1 = getClass().getMethod("myFunc"); // dynamic
Method m2 = this.myFunc; // static
Method m3 = MyClass.myFunc; // static (alternate)
}

我知道上面的语法不起作用,但我想知道是否有某种类似于此的语法确实有效。我想要一种使用反射的方法,而不必担心通过字符串引用方法的固有危险。

有没有办法做到这一点,还是白日做梦?

最佳答案

Method references解释

this method to compare the birth dates of two Person instances already exists as Person.compareByAge. You can invoke this method instead in the body of the lambda expression:

Arrays.sort(rosterAsArray,
(a, b) -> Person.compareByAge(a, b)
);

Because this lambda expression invokes an existing method, you can use a > method reference instead of a lambda expression:

Arrays.sort(rosterAsArray, Person::compareByAge);

它继续解释各种方法引用:

There are four kinds of method references:

Reference to a static method      ContainingClass::staticMethodName

Reference to an instance method
of a particular object containingObject::instanceMethodName

Reference to an instance method ContainingType::methodName
of an arbitrary object of a
particular type

Reference to a constructor ClassName::new

历史记录(写于 Java 8 定稿之前)

我认为 Java 闭包提案有类似的内容。 Stephen Colebourne说:

Stefan and I are pleased to announce the release of v0.4 of the First-class Methods: Java-style closures proposal.

Changes

Since v0.3, we have tried to incorporate some of the feedback received on the various forums. The main changes are as follows:

1) Constructor and Field literals. It is now possible to create type-safe, compile-time changed instances of java.lang.reflect.Constructor and Field using FCM syntax:

// method literal:
Method m = Integer#valueOf(int);

// constructor literal:
Constructor<Integer> c = Integer#(int);

// field literal:
Field f = Integer#MAX_VALUE;

但我不认为这种语法在任何发布的 JVM 中可用。闭包本身绝对不在 Java 7 中。您可能会在 Java 8 中看到它。

Java closures site有指向 "Method references" 的指针虽然看起来他们对语法的更改并不多,但它有点更新。

关于java - 是否可以静态地反射(reflect)一个java方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com