Java 方法名称的有效字符是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10211135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:03:20  来源:igfitidea点击:

What are the valid characters for a Java method name?

javamethodsnamingrules

提问by kon

I read about the naming of Java variables. It says that Java variables cannot start with any numbers and special characters except for $ and _.

我阅读了 Java 变量命名。它说 Java 变量不能以任何数字和特殊字符开头,除了 $ 和 _。

Some valid examples:

一些有效的例子:

int count;
int _count;
int $count;

And some invalid examples:

还有一些无效的例子:

int %count;
int 4count;
int #count;

Do the same rules apply to method names?

相同的规则是否适用于方法名称?

回答by rid

Yes, method names and variable names are what's called "identifiers". Identifiers all share the same rules regarding accepted characters. Take a look at §3.8from the Java Language Specification to find out exactly what an identifier may contain, and §6.2for an explanation about how identifiers are used.

是的,方法名和变量名就是所谓的“标识符”。标识符都共享关于接受字符的相同规则。查看Java 语言规范中的第3.8以准确找出标识符可能包含的内容,并查看第 6.2 节中有关如何使用标识符的说明。

回答by Damian

You might be surprised when having unusual characters for method, such as:

当方法具有不寻常的字符时,您可能会感到惊讶,例如:

public void mój_brzuch_zacznie_burcze?()

and it works pretty nice. Take a look at this blogto see more fancy examples.

它工作得很好。看看这个博客,看看更多奇特的例子。

回答by Ahmed Laatabi

yes, you are right, the same rules are applied for functions.

是的,你是对的,同样的规则适用于函数。

回答by Christian

From the Java Tutorial:

来自 Java 教程:

"Although a method name can be any legal identifier, code conventions restrict method names." http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

“虽然方法名称可以是任何合法标识符,但代码约定限制了方法名称。” http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html