我知道没有办法访问java中的变量链接(如&C或&php)。但例如我有这样的任务:
public class JustTest {
private int n = 1;
private int x = 10;
public int[] getIntegers() {
return new int[] { n, x };
}
public void filledInteger() {
int[] vals = getIntegers();
System.out.println("Before change");
System.out.println(Arrays.toString(vals));
vals[0] = 2;
vals[1] = 20;
System.out.println("After change");
System.out.println(Arrays.toString(vals));
System.out.println("Values of name & xml");
System.out.println(n);
System.out.println(x);
System.out.println("calling getIntegers");
System.out.println(Arrays.toString(getIntegers()));
}
public static void main(String[] args) {
JustTest t = new JustTest();
t.filledInteger();
}
}
结果是:
Before change
[1, 10]
After change
[2, 20]
Values of name & xml
1
10
calling getIntegers
[1, 10]
所以,我想更改类实例的“n”和“x”字段的值。我不能通过直接设置(this->n = 20;)来做到这一点,因为我可能不知道我有哪些字段。只有方法 getIntegers 知道。
(在这段代码中没有,但是例如我有具有自己的字段的子类,并且在父类中我有一个方法filledInteger() 应该更改子类的指定属性(他从方法 getIntegers 知道这个属性是在父类中抽象并在子类中实现))
这是简单的实现(没有继承),使用 php 中的链接
<?php
class JustTest {
private $n = 1;
private $x = 10;
public function getIntegers() {
return array( &$this->n, &$this->x );
}
public function filledInteger() {
$vals = $this->getIntegers();
echo("Before change" . "<br/>");
echo(print_r($vals, true) . "<br/>");
$vals[0] = 2;
$vals[1] = 20;
echo("After change" . "<br/>");
echo(print_r($vals, true) . "<br/>");
echo("Values of n & x". "<br/>");
echo $this->n , "<br/>";
echo $this->x , "<br/>";
echo("call getIntegers again" . "<br/>");
echo(print_r($this->getIntegers(), true) . "<br/>");
}
}
$t = new JustTest();
$t->filledInteger();
?>
结果是:
Before change
Array ( [0] => 1 [1] => 10 )
After change
Array ( [0] => 2 [1] => 20 )
Values of n & x
2
20
call getIntegers again
Array ( [0] => 2 [1] => 20 )
这正是我所需要的。我只是好奇我如何在java中实现这个希望你理解。
下一个例子:
public abstract class ParentTest {
abstract int[] getIntegers();
public void fillIntegers(int[] newIntegers) {
int[] integersOfChild = getIntegers();
for (int i = 0; i < integersOfChild.length; i++) {
integersOfChild[i] = newIntegers[i];
}
}
}
public class ChildTest extends ParentTest {
private int x;
private int y;
@Override
int[] getIntegers() {
return new int[] {x, y};
}
}
public class UseTest {
void main() {
List<ParentTest> list;
for (ParentTest item : list) {
item.fillIntegers(myItegers);
}
}
}
这就是我需要的。我有一个 ParentTest 实例列表(它可能是 ChildTest、ChildTest2 或 ChildTest3;但它们都是 ParentTest 的子项),我需要用我的整数值填充所有字段,但我不知道列表实例中的项目是否ChildTest、ChildTest2 或 ChildTest3 类