如何获得;“所有者实例”;Groovy中类实例的定义?
我有两个类,我想从创建的实例中获取“owner”类的属性,请参阅下面的代码如何获得;“所有者实例”;Groovy中类实例的定义?,groovy,Groovy,我有两个类,我想从创建的实例中获取“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 val
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
}
}
试试这个:
def doSomething(){
A a = new A()
a.test
}
如果没有实例,你就无法得到它。 A班不知道B班的情况。 您可以创建一个以B为参数的构造函数
class A{
A(B b){
println b.test
}
}
然后你可以在B中这样使用它:
doSomething(){
new A(this)
}
不确定这是否是您所追求的,但您可以使用非静态内部类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()
可以将类B的测试属性设置为静态成员变量
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"
我不明白。你希望A如何知道B?我希望创建的实例(类A)获得“所有者”,因此,类B的实例,但类A的实例不应该知道类B。哈哈哈,这不是那么容易,我知道,但我认为是不可能的,在我找到一个解决方案之前,我会像这样使用
A=新A(test:test)
,谢谢你的评论,我不想通过构造函数传递参数,所以,像我想要的那样是不可能的,对吧?这是不可能的。也许有Java反射,但这很疯狂:类B{static Map instances=new HashMap();B(){instances.put(new A(),this)}比你可以在A中使用它,比如:B.instances.get(this)//this=A的实例,但是你应该知道你在做什么,如果你使用它的话。好吧,伙计们,我认为这是不可能的,在我找到一个解决方案之前,我会像这样使用aa=newa(test:test)
谢谢!几乎!这两个类不能有任何关系,这两个类是独立的,我只想“获得所创建类的所有者”,如果可能的话,我肯定它需要一个语言特性,我认为这是不可能的,用变通方法!谢谢你的回答!