在字节码级别对类名唯一的限制是它们不能包含字符[ , . 或; 而且它们最长不超过65535字节。 除此之外,这意味着您可以自由使用保留字,空格,特殊字符,Unicode,甚至是像换行符这样的奇怪的东西。
理论上,甚至可以在类名中使用空字符,但由于在文件名中不能包含空字符,所以不能在jar中包含这样的类文件。 您可能可以创build并加载一个虽然。
下面是你可以做的一些事情的例子(用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
请参阅Holger对JVM规范中规则确切引用的回答 。