繁体   English   中英

java实例变量和具有相同名称的方法

[英]java instance variable and method having same name

在java中,实例变量和方法是否具有相同的名称,没有任何不稳定或冲突?

我想确定我是否可以逃脱编译,它不会导致任何错误。

是的,没关系,主要是因为从语法上讲,它们的使用方式不同。

它完全没问题,因为方法和变量的调用方式不同。

码:

String name = "myVariable";

public String name() {
    return "myMethod";
}

System.out.println(name()); // Brackets for method call
System.out.println(name); // No brackets for variable call

输出:

myMethod的

MYVARIABLE

我能想到的唯一冲突是

int sameName = 5;

public int sameName() {
  //method body
  return 100;
}

如果你写“this.sameName”时,你应该写“this.sameName()”, 反之亦然在程序的某个地方,然后代码湮灭才刚刚开始。

我实际上遇到了一个非常具体的问题。 它只是在Java 8中使用(使用Nashorn),而在Java 6中使用(使用Rhino)。 如果它尝试通过Javascript访问Java对象的实例变量,则[]运算符将返回方法实例。

假设我正在运行以下Java声明:

class MyClass {
    private boolean isSet=false;
    public boolean isSet() { return isSet; }
}

如果我在Javascript中操作这样的类的对象,然后尝试使用[]运算符访问它,我得到方法引用。

var obj = new MyClass();
var myfields = (myclass.getClass()).getDeclaredFields();
var myfieldname = myfields[0].name;

// The following prints the method declaration, not the boolean value:
// [jdk.internal.dynalink.beans.SimpleDynamicMethod boolean MyClass.isSet()]
println( obj[myfieldname] );

更新:显然Nashorn的方法重载解析机制 (“隐式”或非故意 )为没有参数的方法提供了更高的优先级,而不是具有相同名称的实例字段。

您可以,但它是一种反模式,应该避免,并且可以被分析抓住,如下所示:

http://pmd.sourceforge.net/pmd-4.3.0/rules/naming.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM