为什么以下产生NoSuchMethodException
:
Welcome to Scala 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_92).
Type in expressions for evaluation. Or try :help.
scala> class Test(val i: Int = 5)
defined class Test
scala> classOf[Test].getDeclaredConstructor()
java.lang.NoSuchMethodException: Test.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
... 32 elided
即使我可以轻松做到:
scala> new Test()
res0: Test = Test@707f7052
scala> res0.i
res1: Int = 5
javap不是很有帮助:
scala> :javap Test
Size 579 bytes
MD5 checksum 20263ec5d03959f8477847f3d71b324e
Compiled from "<console>"
public class Test
minor version: 0
major version: 50
flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
#1 = Utf8 Test
#2 = Class #1 // Test
#3 = Utf8 java/lang/Object
#4 = Class #3 // java/lang/Object
#5 = Utf8 <console>
#6 = Utf8 i
#7 = Utf8 I
#8 = Utf8 ()I
#9 = NameAndType #6:#7 // i:I
#10 = Fieldref #2.#9 // Test.i:I
#11 = Utf8 this
#12 = Utf8 LTest;
#13 = Utf8 <init>
#14 = Utf8 (I)V
#15 = Utf8 ()V
#16 = NameAndType #13:#15 // "<init>":()V
#17 = Methodref #4.#16 // java/lang/Object."<init>":()V
#18 = Utf8
#19 = Class #18 //
#20 = Utf8 $line6/$read
#21 = Class #20 // $line6/$read
#22 = Utf8
#23 = Utf8
#24 = Class #23 //
#25 = Utf8 Test
#26 = Utf8 Code
#27 = Utf8 LocalVariableTable
#28 = Utf8 LineNumberTable
#29 = Utf8 SourceFile
#30 = Utf8 InnerClasses
#31 = Utf8 ScalaInlineInfo
#32 = Utf8 Scala
{
public int i();
descriptor: ()I
flags: ACC_PUBLIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: getfield #10 // Field i:I
4: ireturn
LocalVariableTable:
Start Length Slot Name Signature
0 5 0 this LTest;
LineNumberTable:
line 11: 0
public Test(int);
descriptor: (I)V
flags: ACC_PUBLIC
Code:
stack=2, locals=2, args_size=2
0: aload_0
1: iload_1
2: putfield #10 // Field i:I
5: aload_0
6: invokespecial #17 // Method java/lang/Object."<init>":()V
9: return
LocalVariableTable:
Start Length Slot Name Signature
0 10 0 this LTest;
0 10 1 i I
LineNumberTable:
line 11: 0
line 14: 5
}
SourceFile: "<console>"
InnerClasses:
public static #22= #19 of #21; //=class of class $line6/$read
public static #22= #24 of #19; //=class of class
public static #25= #2 of #24; //Test=class Test of class
Error: unknown attribute
ScalaInlineInfo: length = 0xE
01 00 00 02 00 0D 00 0E 00 00 06 00 08 00
Error: unknown attribute
Scala: length = 0x0
似乎只有一个构造函数接受一个int。 我怀疑魔法scala的表现隐藏在其中一个InnerClasses中,但我不知道如何检查它们。
PS:如果字段i
未使用val
声明,则getDeclaredConstructor()输出相同。