我在Fragment的部分阅读了一些Android代码,并试图找出它背后的逻辑。我班上有一个接口。我想基于某些条件,接口方法的String值发生变化。
例如,使用cond=false
,代码不会编译。我正在寻找一种具有相同结构的方法来使其发挥作用:
这是测试类:
public class Test {
InnerInterface interInstance;
public interface InnerInterface {
public String interfaceMethod(String s);
}
public void update() {
String time = String.valueOf(System.currentTimeMillis());
interInstance.interfaceMethod(time);
}
public static void main(String[] args) {
boolean cond = true;
Activity a = new Activity();
Test t = new Test();
if (cond)
System.out.println(a.interfaceMethod("John"));
else
// this won't work of course
t.update();
System.out.println(a.interfaceMethod("Doe"));
}
}
这里是Activity类:
public class Activity implements Test.InnerInterface{
@Override
public String interfaceMethod(String s) {
String actString = s;
return actString;
}
}
答案 0 :(得分:0)
那怎么样?
public static void main(String[] args) {
boolean cond = false;
Activity a = new Activity();
Test t = new Test();
t.interInstance=a; //Add this line to your code
if (cond)
System.out.println(a.interfaceMethod("John"));
else
t.update(); //interInstance mustn't be null at this point
System.out.println(t.interInstance.interfaceMethod("Doe"));
}