如题,,,
[b]问题补充:[/b]
晕 不是 啊。不是 一开始 就赋值 比如 类.属性=“1” 这样赋值过以后 就不然在 类.属性=“2” 或者 new 等其他 赋值的操作
[b]问题补充:[/b]
不要说 判断 不是1 就 RETURN 我只想 他赋过值 以后 就强制不许他赋值的操作 而不是 在于 他的value
[b]问题补充:[/b]
晕 我也不要这样的效果啊。 这样做判断 那自然可以的 但我想的是 是不是可以直接通过java的语法 等等 强制性的 不要逻辑判断
[b]问题补充:[/b]
我想知道有没有这样的 语法的 才问的
你的问题实际上是 运行 时, 只赋值一次。
动态时,是代码已经生成,
这种逻辑检查,是 你代码来保证的。
不是java语法检查能处理的了。
投机方法:
只有第一次赋值有效。(不知道有什么用)
public class FinalTest {
private static String value;
private static class Holder {
private static final String str = value;
}
public static void setValue(String value) {
FinalTest.value = value;
System.out.println(Holder.str); //加载内部类
}
public static void main(String[] args) {
setValue("123");
System.out.println(Holder.str);
setValue("123123");
System.out.println(Holder.str);
}
}
简单呀 声明为final即可
如将某些常量声明为:
private static final String UNAME = "zhangsan";
[code="java"]public class A {
private Integer t = null;
public void setT(Integer target) throws Exception {
if (t==null) {
this.t=target;
} else {
throw new Exception("has value");
}
}
}
[/code]
[code="java"]public class A {
private boolean tInited=false;
private Integer t = null;
public void setT(Integer target) throws Exception {
if (tInited) {
throw new Exception("has value");
} else {
tInited=true;
this.t=target;
}
}
}
[/code]
楼主看看以下code,不知道是不是你想要的结果
[code="java"]
public class Test1 {
private static int id;
public static int setValue(int args) {
if (id > 0) {
return id;
}
id = args;
return id;
}
}
public class Test2 {
public static void main(String[] args) {
System.out.println(Test1.setValue(5));
System.out.println(Test1.setValue(6));
System.out.println(Test1.setValue(7));
Test1 t1=new Test1();
System.out.println(t1.setValue(8));
}
}
输出结果都是5
[/code]