问题描述
我正在使用Java 15的新记录功能,以及它如何与反射交互。我遇到了一些奇怪的行为,有时可以通过反射访问记录的构造函数,有时不能。例如,给定以下Java文件:
Recording.java
:
public class Recording {
public static void main(String[] args) {
System.out.println("Constructors: " + MainRecord.class.getConstructors().length);
System.out.println("Methods: " + MainRecord.class.getDeclaredMethods().length);
}
record MainRecord(int i,String s) {}
}
其行为如下:
❯ javac --enable-preview --release 15 Recording.java
Note: Recording.java uses preview language features.
Note: Recompile with -Xlint:preview for details.
❯ java --enable-preview Recording
Constructors: 0
Methods: 5
换句话说,对getConstructors()
的调用没有找到任何构造函数(而对`getDeclaredMethods()的调用却找到了方法)。我不明白为什么不这样做,因为构造函数确实存在:
❯ javap Recording\$MainRecord
Compiled from "Recording.java"
final class Recording$MainRecord extends java.lang.Record {
Recording$MainRecord(int,java.lang.String);
public final java.lang.String toString();
public final int hashCode();
public final boolean equals(java.lang.Object);
public int i();
public java.lang.String s();
}
(将记录放在单独的Java文件中会得到相同的结果。)
但是,如果我从JShell中执行相同操作:
❯ jshell --enable-preview
| Welcome to JShell -- Version 15
| For an introduction type: /help intro
jshell> record JShellRecord(int i,String s) {}
| created record JShellRecord
jshell> JShellRecord.class.getConstructors().length
$2 ==> 1
因此,现在它确实找到了构造函数。
这是我正在使用的Java版本:
❯ java -version
openjdk version "15" 2020-09-15
OpenJDK Runtime Environment AdoptOpenJDK (build 15+36)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 15+36,mixed mode,sharing)
从Java 14编译并运行相同程序确实可以:
❯ java -version
openjdk version "14.0.2" 2020-07-14
OpenJDK Runtime Environment AdoptOpenJDK (build 14.0.2+12)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 14.0.2+12,sharing)
❯ javac --enable-preview --release 14 Recording.java
Note: Recording.java uses preview language features.
Note: Recompile with -Xlint:preview for details.
❯ java --enable-preview Recording
Constructors: 1
Methods: 5
我知道在Java 15中,与Java 14相比,在记录反射方面已设置了许多限制,但是如果我正确阅读JEP,则这些限制仅适用于修改。查找(也许调用)构造函数似乎并不适用。
谁能告诉我这是怎么回事?要通过反射查看Java 15中记录的构造函数,我需要做些什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)