我有两个类,我想从创建的实例中获取“owner”类的属性,请参阅下面的代码......
class A{
String test
A(){
//How to get the value of "test" property of the class B from here?
//
}
}
class B{
String test
def doSomething(){
//I'd like that instance of A get the value of "test" attribute without pass it by param
A a = new A() //like this
A a = new A(test:test) //I don't want to do this
}
}
答案 0 :(得分:0)
试试这个:
def doSomething(){
A a = new A()
a.test
}
答案 1 :(得分:0)
没有实例你就无法得到它。 A班不了解B班。 您可以使用B作为参数创建构造函数。
class A{
A(B b){
println b.test
}
}
然后你可以在B中使用它:
doSomething(){
new A(this)
}
答案 2 :(得分:0)
不确定这是否是您所追求的,但您可以使用非静态内部类A拥有一种所有权关系。在Groovy中使用与Java相同的工作。
class B {
class A {
def knowYourOwner() {
// access the outer class' property directly via test
println "My owner says: '$test'"
// or explicitly via B.this.test (to avoid conflicts with local variables 'test')
def test = 'another string'
println "My owner says: '${B.this.test}'"
}
}
String test
def doSomething() {
A a = new A()
a.knowYourOwner()
}
}
def b = new B(test: 'I am B')
b.doSomething()
答案 3 :(得分:0)
您可以将B类的test属性设为静态成员变量
class A {
String test
A() {
this.test = B.test
}
}
class B {
static String test
}
def b = new B(test: "someString")
def a = new A()
println a.test // outputs : "someString"