gpt4 book ai didi

java - 在Java方法引用中是反射API的一部分

转载 作者:行者123 更新时间:2023-11-30 02:19:19 25 4
gpt4 key购买 nike

在 Kotlin 中,方法引用的结果放置在 kotlin.reflect 包中。 Java中的方法引用也是反射API的一部分吗?

最佳答案

故意未指定实现方法引用的功能接口(interface)的实际类型。重要的是,它是由当前的 JRE 提供的。

实际上,对于 HotSpot/OpenJDK,它是运行时生成的类,与包含方法引用的类驻留在同一包和类加载上下文中。它不继承自特殊的类,并且除了其目标类型定义的接口(interface)之外,不实现其他接口(interface)。因此,虽然这个类有一些特殊的属性,即它不能通过名称查找,并且无论其定义的类加载器是否可达,它都可能被垃圾回收,但它不是 Reflection API 的一部分。

为方法引用创建的实例的属性由the Java Language Specification指定。如下:

The value of a method reference expression is a reference to an instance of a class with the following properties:

  • The class implements the targeted functional interface type and, if the target type is an intersection type, every other interface type mentioned in the intersection.

  • Where the method reference expression has type U, for each non-static member method m of U:

    If the function type of U has a subsignature of the signature of m, then the class declares an invocation method that overrides m. The invocation method's body invokes the referenced method, creates a class instance, or creates an array, as described below. If the invocation method's result is not void, then the body returns the result of the method invocation or object creation, after any necessary assignment conversions (§5.2).

    If the erasure of the type of a method being overridden differs in its signature from the erasure of the function type of U, then before the method invocation or object creation, an invocation method's body checks that each argument value is an instance of a subclass or subinterface of the erasure of the corresponding parameter type in the function type of U; if not, a ClassCastException is thrown.

  • The class overrides no other methods of the functional interface type or other interface types mentioned above, although it may override methods of the Object class.

关于java - 在Java方法引用中是反射API的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47304096/

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