gpt4 book ai didi

Java记录反射和合成方法

转载 作者:行者123 更新时间:2023-12-02 15:43:14 27 4
gpt4 key购买 nike

基于旧的Java (7) Language Specifications (13.1.7) :

Any constructs introduced by a Java compiler that do not have a corresponding construct in the source code must be marked as synthetic, except for default constructors, the class initialization method, and the values and valueOf methods of the Enum class.

在较新的 ( Java (17) Language Specifications (13.1.7) : ) 上,措辞更改为:

A construct emitted by a Java compiler must be marked as synthetic if it does not correspond to a construct declared explicitly or implicitly in source code, unless the emitted construct is a class initialization method (JVMS §2.9).

我想知道这如何应用于为 java Records (JEP 395) 的组件创建的访问器方法

例如

record ARecord(int a){}

会有一个方法 int a() 但没有代码表示这种方法,根据旧 JLS 的措辞,这种方法是由编译器添加的,所以我希望它是合成的但事实并非如此,因为可以通过在 JShell 上运行以下两行来证实这一点

jshell
| Welcome to JShell -- Version 17.0.1
| For an introduction type: /help intro

jshell> record ARecord(int a){}
| created record ARecord

jshell> ARecord.class.getDeclaredMethod("a").isSynthetic();
$2 ==> false

jshell>

我问的原因是因为我想在运行时使用反射(或任何其他编程方式)来确定类中的哪些元素具有匹配的代码结构,基本上那些具有代表它们的代码,意思是:

对于下面的代码

record ARecord(int a){

pubic void someMethod() {}

}

entity 将有 2 个方法(asomeMethod),a 没有代表它的代码并且someMethod 确实如此,我需要一种方法来根据该标准区分那些

最佳答案

I wonder if it is because its considered as implicitly declared being its code implicitly defined as part of the component

就是这样。请注意旧规范如何只说“合成”应该标记在构造上

do not have a corresponding construct in the source code

隐式声明的 Enum.valuesEnum.valueOf 除外。那时候,显然只有这两个是隐式声明的(在新规范使用该短语的意义上)。 :D

另一方面,新规范说

does not correspond to a construct declared explicitly or implicitly in source code

请注意,此措辞会自动处理 Enum 异常,但也会处理此后添加的大量隐式声明的内容。这包括记录组件。

来自Java 17 spec §8.10.3. Record Members ,

Furthermore, for each record component, a record class has a method with the same name as the record component and an empty formal parameter list. This method, which is declared explicitly or implicitly, is known as an accessor method.

...

If a record class has a record component for which an accessor method is not declared explicitly, then an accessor method for that record component is declared implicitly [...]

a 方法在您的组件中隐式声明,因此它不是合成的。

一般来说(可能存在我不知道的异常(exception)情况),合成结构是语言规范未指定但特定实现所必需的结构编译器工作。规范基本上是说此类结构必须在二进制文件中标记为“合成的”。查看一些示例 here .

关于Java记录反射和合成方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75293090/

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