簡介:Method References
Java8 的 lambda 表達(dá)式 可以很方便的用來創(chuàng)建一個匿名方法。在更多的情況下哮兰,可以通過一種新的 方法引用 的語法來基于一個現(xiàn)有的方法創(chuàng)建一個新的 lambda 表達(dá)式。
例如:某個方法需要傳入一個 java.util.function.Supplier<Long>
:
setTimeStampSupplier(Supplier<Long> supplier);
假如我們打算為這個方法提供一個總是返回系統(tǒng)當(dāng)前時間戳的 supplier,那么在按照傳統(tǒng)的方法書寫:
obj.setTimeStampSupplier(new Supplier<Long>() {
@Override
public Long get() {
return System.currentTimeMillis();
}
});
由于 java.util.function.Supplier
是一個 FunctionalInterface,所以可以使用 Lambda 表達(dá)式的方式來簡化書寫:
obj.setTimeStampSupplier(() -> System.currentTimeMillis());
借由 Method References 語法的幫助钝的,這種寫法可以更加簡化為:
obj.setTimeStampSupplier(System::currentTimeMillis);
上文中的 System::currentTimeMillis
就是一個方法引用翁垂。
獲取 Method Reference 所引用的 Method 實(shí)例
理論分析
那么是否能在運(yùn)行時獲取某個給定的 Method Reference 所引用的 java.lang.reflect.Method
實(shí)例呢?
答案是:沒有可靠的硝桩、完美的方法(來自:Mike Strobel 的回答)
Java 實(shí)現(xiàn) Lambda Expression 的方式并不是引入了一個新的數(shù)據(jù)類型沮峡,而可以理解成 JVM 在運(yùn)行時動態(tài)生成匿名類(實(shí)際上是通過 invokedynamic
指令實(shí)現(xiàn)的,具體可以參閱 Java 8 Lambdas - A Peek Under the Hood
這篇文章亿柑,這樣效率比匿名類要高很多,不過不妨礙理解)棍弄,因此在這一機(jī)制下望薄,在語言層面上 Method Reference 和 Method 并沒有一一對應(yīng)的關(guān)系,因此也沒有可靠的方法能夠完美獲取 Method Reference 所引用的 Method呼畸。
“沒有可靠的方法” 并不等于 “沒有方法”
如題痕支,沒有可靠的完美的方法 并不等于 沒有方法。在滿足某些特定的條件下蛮原,是可以的通過 Method Reference 獲取到其引用的方法的卧须。
Method Reference 可以分成下面四種類型:
種類 | 例子 |
---|---|
引用給定類型上的靜態(tài)方法 |
ContainingClass::staticMethodName ,例如:java.lang.Thread::currentThread
|
引用給定對象上的實(shí)例方法 |
containingObject::instanceMethodName 儒陨,例如:java.lang.Thread.currentThread::getName
|
引用給定類型上的實(shí)例方法 |
ContainingType::methodName 花嘶,例如:java.lang.Thread::getId
|
引用構(gòu)造函數(shù) |
ClassName::new ,例如:java.lang.Object::new
|
上表中第一類和第三類的區(qū)別在于(以例子中的方法為例):
- 第一類 Method Reference 將匹配形如
Supplier<Thread>
的函數(shù)式接口- 第三類 Method Reference 將匹配形如
Function<Thread, Long>
或者Consumer<Thread>
的函數(shù)式接口
如果給定的 MethodReference 是上表中的第二類或者第三類蹦漠,并且滿足:
- 給定的類或者給定對象的類不是
final
類椭员,并且最好需要有一個有效的無參數(shù)構(gòu)造函數(shù),或者給定的類為接口 - 指定的實(shí)例方法不是
final
方法
在這種情況下笛园,可以借助 cglib 來創(chuàng)建一個給定類的實(shí)例隘击,并攔截給定的方法,然后在此實(shí)例上調(diào)用給定的 MethodReference研铆,于是就可以在攔截器中獲取 Method 實(shí)例了埋同。(這也就解釋了為什么會有上面的限制,因?yàn)?cglib 的 Enhancer 無法創(chuàng)建一個 final 類的子類棵红,也無法攔截一個 final 方法)
代碼實(shí)例
假定我們要獲取 Thread::getId
引用的 Method凶赁,那么可以使用如下的代碼:
// 定義一個 MethodReference
Function<Thread, Long> methodRef = Thread::getId;
// 創(chuàng)建一個 Enhancer,并配置攔截器
AtomicReference<Method> ref = new AtomicReference<Method>();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(Thread.class);
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
ref.set(method);
return null;
}
});
// 創(chuàng)建一個實(shí)例
Thread phantom = (Thread) enhancer.create();
// 在實(shí)例上調(diào)用 MethodReference
methodRef.apply(phantom);
Method method = ref.get();
System.out.println(method);
運(yùn)行結(jié)果:
public long java.lang.Thread.getId()
優(yōu)化
重構(gòu)為庫函數(shù)
有了上面的原型以后窄赋,我們可以重構(gòu)出一個獲取 帶返回值但是無參數(shù)的實(shí)例方法 的 Method Reference 的 Method 的庫函數(shù):
public static <T, R> Method getReferencedMethod(Class<T> clazz, Function<T, R> methodRef) {
// 創(chuàng)建一個 Enhancer哟冬,并配置攔截器
AtomicReference<Method> ref = new AtomicReference<Method>();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
ref.set(method);
return null;
}
});
// 創(chuàng)建一個實(shí)例
@SuppressWarnings("unchecked")
T phantom = (T) enhancer.create();
// 在實(shí)例上調(diào)用 MethodReference
methodRef.apply(phantom);
Method method = ref.get();
if (method == null) {
// 如果傳入的不是方法引用,而是直接 new 出來的 Function 實(shí)例忆绰,那么 method 就會是 null
throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
}
return method;
}
只需要如此調(diào)用即可:getReferencedMethod(Thread.class, Thread::getId)
浩峡。
再進(jìn)一步,適配滿足條件的任何情況
上述的庫函數(shù)只能用于獲取帶返回值但是無參數(shù)的實(shí)例方法错敢,如果遇到其它情況的實(shí)例方法的時候應(yīng)該怎么辦呢翰灾?
這個時候我們需要再將上面的庫函數(shù)進(jìn)一步抽象缕粹,然后通過為目標(biāo)實(shí)例方法來定義函數(shù)式接口來實(shí)現(xiàn)。
首先抽象 getReferencedMethod
函數(shù):
public static <T> Method getReferencedMethod(Class<T> clazz, Consumer<? super T> invoker) {
// 創(chuàng)建一個 Enhancer纸淮,并配置攔截器
AtomicReference<Method> ref = new AtomicReference<Method>();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
ref.set(method);
return null;
}
});
// 創(chuàng)建一個實(shí)例
@SuppressWarnings("unchecked")
T phantom = (T) enhancer.create();
// invoker 需要在實(shí)例上調(diào)用 MethodReference
invoker.accept(phantom);
Method method = ref.get();
if (method == null) {
// 如果傳入的不是方法引用平斩,而是直接 new 出來的 Function 實(shí)例,那么 method 就會是 null
throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
}
return method;
}
接下來咽块,我們需要為特定的目標(biāo)實(shí)例方法創(chuàng)建一個函數(shù)式接口绘面,使其能夠接納這個實(shí)例方法的 MethodReference。假定我們需要適配 NavigableMap::subMap(K fromKey, K toKey)
侈沪,那么我們可以定義如下的函數(shù)式接口:
/**
* 一個可以匹配帶有兩個參數(shù)的實(shí)例方法引用的函數(shù)式接口
*/
@FunctionalInterface
public interface MethodRefWith2Args<T, A1, A2> {
void accept(T instance, A1 arg1, A2 arg2) throws Exception;
}
然后我們創(chuàng)建一個 Consumer
用來調(diào)用 Method Reference揭璃,最后將他們封裝在一起,一個嶄新的亭罪、用來匹配帶兩個參數(shù)的方法的 MethodReference 的 getReferencedMethod 誕生了:
public static <T, A1, A2> Method getReferencedMethod(
Class<T> clazz,
MethodRefWith2Args<? super T, A1, A2> methodRef) {
return getReferencedMethod(clazz, phantom -> {
try {
// 后面參數(shù)傳 null 沒關(guān)系瘦馍,因?yàn)閷?shí)際被調(diào)用的是我們自己的 MethodInterceptor
// 不會去處理參數(shù)
// 不過如果參數(shù)類型是 primitive 的話,這里會拋出 NullPointerException
methodRef.accept(phantom, null, null);
} catch (Exception e) {
// 正常情況下应役,不會跑到這里來
}
});
}
舉一反三
如果工程中需要用此方法獲取方法實(shí)例的目標(biāo)實(shí)例方法并沒有太多參數(shù)情组,那么其實(shí)可以預(yù)先定義好一堆的適配用的函數(shù)式接口,譬如:MethodRefWith3Args
箩祥、MethodRefWith4Args
院崇、MethodRefWith5Args
、MethodRefWith6Args
……袍祖,在大多數(shù)情況下就夠用了亚脆。
不過仍然不能大意。如果目標(biāo)實(shí)例方法的某個參數(shù)是 primitive 類型(例如 int
而非 Integer
)盲泛,在撰寫用來實(shí)際調(diào)用 methodReference 的 invoker (即基礎(chǔ)的 getReferencedMethod
的第二個參數(shù))的時候需要特殊處理濒持。不能一股腦兒傳 null 了。
例如需要匹配的實(shí)例方法是 NavigableMap.headMap(K toKey, boolean inclusive)
寺滚,那么用前面的例子就不行柑营,需要修改成:
public static <T, A1, A2> Method getReferencedMethod(
Class<T> clazz,
MethodRefWith2Args<? super T, A1, A2> methodRef) {
return getReferencedMethod(clazz, phantom -> {
try {
// 注意第三個參數(shù),必須是一個非 null 的值
// 否則在 unboxing 的時候會拋出 NullPointerException
methodRef.accept(phantom, null, new Boolean());
} catch (Exception e) {
// 正常情況下村视,不會跑到這里來
}
});
}
后記
有興趣的可以看看 StackOverflow 上的問題:How to get the MethodInfo of a Java 8 method reference? 在這個問題中我也有簡略作答官套。