我知道Java可编译程序设计语言不是一种与JVM执行Java字节码格式相同的语言。有些示例在.class格式中有效,但在.java源代码中无效,例如无构造函数的类和合成方法。
如果我们的手工工艺.class文件有保留的Java语言的关键字(例如int
,while
)作为类,方法或字段名,将在Java虚拟机接受它加载?
如果加载了该类,是否意味着访问该类或成员的唯一方法是通过Java反射,因为该名称在Java编程语言中在语法上是非法的?
在字节码级别上对类名称的唯一限制是它们不能包含字符[
,.
或者;
它们的最大长度为65535字节。除其他外,这意味着您可以自由使用保留字,空格,特殊字符,Unicode甚至是换行符之类的怪异东西。
从理论上讲,您甚至可以在类名称中使用空字符,但是由于文件名中不可能包含空字符,因此您不能在jar中包含这样的类文件。您也许可以动态创建和加载一个。
这是您可以做的一些事情的示例(用Krakatau程序集编写):
; Entry point for the jar
.class Main
.super java/lang/Object
.method public static main : ([Ljava/lang/String;)V
.limit stack 10
.limit locals 10
invokestatic int hello ()V
invokestatic "-42" hello ()V
invokestatic "" hello ()V
invokestatic " some whitespace and \t tabs" hello ()V
invokestatic "new\nline" hello ()V
invokestatic 'name with "Quotes" in it' hello ()V
return
.end method
.end class
.class int
.super java/lang/Object
.method public static hello : ()V
.limit stack 2
.limit locals 0
getstatic java/lang/System out Ljava/io/PrintStream;
ldc "Hello from int"
invokevirtual java/io/PrintStream println (Ljava/lang/Object;)V
return
.end method
.end class
.class "-42"
.super java/lang/Object
.method public static hello : ()V
.limit stack 2
.limit locals 0
getstatic java/lang/System out Ljava/io/PrintStream;
ldc "Hello from -42"
invokevirtual java/io/PrintStream println (Ljava/lang/Object;)V
return
.end method
.end class
; Even the empty string can be a class name!
.class ""
.super java/lang/Object
.method public static hello : ()V
.limit stack 2
.limit locals 0
getstatic java/lang/System out Ljava/io/PrintStream;
ldc "Hello from "
invokevirtual java/io/PrintStream println (Ljava/lang/Object;)V
return
.end method
.end class
.class " some whitespace and \t tabs"
.super java/lang/Object
.method public static hello : ()V
.limit stack 2
.limit locals 0
getstatic java/lang/System out Ljava/io/PrintStream;
ldc "Hello from some whitespace and \t tabs"
invokevirtual java/io/PrintStream println (Ljava/lang/Object;)V
return
.end method
.end class
.class "new\nline"
.super java/lang/Object
.method public static hello : ()V
.limit stack 2
.limit locals 0
getstatic java/lang/System out Ljava/io/PrintStream;
ldc "Hello from new\nline"
invokevirtual java/io/PrintStream println (Ljava/lang/Object;)V
return
.end method
.end class
.class 'name with "Quotes" in it'
.super java/lang/Object
.method public static hello : ()V
.limit stack 2
.limit locals 0
getstatic java/lang/System out Ljava/io/PrintStream;
ldc "Hello from name with \"Quotes\" in it"
invokevirtual java/io/PrintStream println (Ljava/lang/Object;)V
return
.end method
.end class
执行输出:
Hello from int
Hello from -42
Hello from
Hello from some whitespace and tabs
Hello from new
line
Hello from name with "Quotes" in it
有关JVM规范中规则的确切引用,请参见Holger的答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句