Max name length of variable or method in Java

北战南征 提交于 2019-11-26 23:06:08

问题


Is there a max length for class/method/variable names in Java? the JLS doesn't seem to mention that. I know very long names are problematic anyway from code readability and maintainability perspective, but just out of curiosity is there a limitation (I guess class names might be limited by the file system maximal file name limitation).


回答1:


If I'm not mistaken, the limit is not in the language itself but in the classfile format, which limits names to 64k, so for all practical intents and purposes identifier length is not a problem. Specifically, this is the definition of a constant string in the pool, which seems to imply the maximal length is 16 bit:

CONSTANT_Utf8_info {
    u1 tag;
    u2 length;
    u1 bytes[length];
}

Class names may be more of an issue for file systems, I agree, I'm not sure what's currently supported.




回答2:


Sorry, actually found the answer in the JLS: http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#40625 It seems that identifier names are of unlimited length.

Also found similar question (though it didn't appear in my initial search, or when I typed the question title which is weird): Maximum Method Name Length




回答3:


If you go over the size limit imposed by the VM for method names then you get a compiler error (at least with the version of javac I am using):

Main.java:1: UTF8 representation for string "aaaaaaaaaaaaaaaaaaaa..." is too long for the constant pool



来源:https://stackoverflow.com/questions/695951/max-name-length-of-variable-or-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!