当您在变量上放置注释时,它成为该变量的静态属性,而不是您可以通过该变量访问的对象的静态属性。考虑:
public class A1 extends myA{
@Test("all")
private B b1=new B();
@Test("none")
private B b2=b1;
//....
public void interact(){
// this
b2.doSomethingBasedOnMyAnnotation();
// is exactly the same as
b1.doSomethingBasedOnMyAnnotation();
}
}
假设涉及一个带注释的变量甚至是无效的。怎么样
new B().doSomethingBasedOnMyAnnotation()
?
由于字段是在编译时解析的,因此在您想要的操作中无论如何都没有抽象。如果您知道要调用 , b2.doSomethingBasedOnMyAnnotation();
,则您已经知道您正在使用哪个字段,并且将 as 参数的注释值提供给被调用的方法是没有问题的b2
,而不是期望接收者神奇地发现。例如
public class B{
public void doSomething(String arg){
}
}
public class A1 extends myA{
@Test("all")
private B b1;
@Test("none")
private B b2;
//....
public void interact(){
b1.doSomething(get("b1"));
b2.doSomething(get("b2"));
}
static String get(String fieldName) {
try {
return A1.class.getDeclaredField(fieldName)
.getAnnotation(Test.class).value();
} catch(NoSuchFieldException ex) {
throw new IllegalStateException(ex);
}
}
}
尽管我们可以在没有反射的情况下愉快地工作:
public class A1 extends myA{
static final String TEST_B1="all";
@Test(TEST_B1)
private B b1;
static final String TEST_B2="none";
@Test(TEST_B2)
private B b2;
static final String TEST_B3="none";
@Test(TEST_B3)
private B b3;
//....
public void interact(){
b1.doSomething(TEST_B1);
b2.doSomething(TEST_B2);
}
}
如果您想确保调用者不会意外传递错误的参数,请改用封装:
public final class EncapsulatedB {
final String testValue;
B b;
EncapsulatedB(String value) {
this(value, null);
}
EncapsulatedB(String value, B initialB) {
testValue=value;
b=initialB;
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
public void doSomething() {
b.doSomething(testValue);
}
}
public class A1 extends myA{
private final EncapsulatedB b1=new EncapsulatedB("all");
private final EncapsulatedB b2=new EncapsulatedB("none");
private final EncapsulatedB b3=new EncapsulatedB("none");
//....
public void interact(){
b1.doSomething();
b2.doSomething();
}
}