switch不是循环,代码走到case 1遇到break;后自然会中断switch并执行switch之后的代码。如果你非要这样做,可以利用java引用对象来做。
静态变量(全局引用,一次实例化)
public class $ {
public static Test t = new Test();
public static void main(String[] args) {
test(1);
test(2);
}
public static void test(int i) {
switch (i) {
case 1:
if(t == null) t = new Test();
t.str = "你好";
break;
case 2:
System.out.println(t.str);
break;
default:
break;
}
}
}
class Test {
int a = 12;
String str = "Hello";
}
或者将对象带入方法(带入方法的对象必须保证不为null,否则空指针异常)
public class $ {
public static void main(String[] args) {
Test t = new Test();
test(t, 1);
test(t, 2);
}
public static void test(Test t, int i) {
switch (i) {
case 1:
if(t == null) t = new Test();
t.str = "你好";
break;
case 2:
System.out.println(t.str);
break;
default:
break;
}
}
}
class Test {
int a = 12;
String str = "Hello";
}