看到评论里很多人都说没有用,还有觉得去掉这个方法,那个方法的解决方案,在这个
例子中怎么改都行,因为这个例子是我乱编的,我真正要说的是一种解决方案。
同志们呀,
要领会精神!
我们的程序有时可能会被无意的进行了攻击,现在就来举个被攻击的例子,说明如何防御。
先创建一个工作类Work,只有一个简单的工资属性salary
public class Work{
private int salary;
public Work(int salary){
this.salary=salary;
}
public void setSalary(int salary){
this.salary=salary;
}
public int getSalary(){
return salary;
}
public String toString(){
return "work.salary:"+salary;
}
}
在创建一个人员类Person,有人员姓名、工作两个属性
public class Person{
private final String name;
private final Work work;
public Person(String name,Work work){
if(work.getSalary()<0) throw new IllegalArgumentException(" 工作的工资不能小于0");
this.name=name;
this.work=work;
}
public Work getWork(){
return work;
}
public String toString(){
return "name:"+name+" work:"+work;
}
}
这个类已经很小心了,已经控制工作的工资不能小于0了。
我现在来一个简单的调用
public class Test{
public static void main(String[] args){
Work work =new Work(3000);
Person person=new Person("taoge",work);
System.out.println(person);
}
}
输出结果为
name:taoge work:work.salary:3000
目前一切都很正常,现在我来进行攻击。
调用代码改为
public class Test{
public static void main(String[] args){
Work work =new Work(3000);
Person person=new Person("taoge",work);
System.out.println(person);
work.setSalary(-1);
System.out.println(person);
}
}
再来看看输出结果
name:taoge work:work.salary:3000
name:taoge work:work.salary:-1
完蛋了,工资竟然变成负值了。看来攻击很成功,现在进行防守了。
将Person类行进改造
public class Person{
private final String name;
private final Work work;
public Person(String name,Work work){
if(work.getSalary()<0) throw new IllegalArgumentException(" 工作的工资不能小于0");
this.name=name;
//this.work=work;
this.work=new Work(work.getSalary());
}
public Work getWork(){
return work;
}
public String toString(){
return "name:"+name+" work:"+work;
}
}
在执行下,看看结果
name:taoge work:work.salary:3000
name:taoge work:work.salary:3000
哈,不错,防守成功。
那我开始进行第二轮进攻了,攻击代码做如下修改
public class Test{
public static void main(String[] args){
Work work =new Work(3000);
Person person=new Person("taoge",work);
System.out.println(person);
//work.setSalary(-1);
person.getWork().setSalary(-1);
System.out.println(person);
}
}
在看看执行结果
name:taoge work:work.salary:3000
name:taoge work:work.salary:-1
又一次攻击成功,那我进行新一轮的防守了,Person代码做如下修改
public class Person{
private final String name;
private final Work work;
public Person(String name,Work work){
if(work.getSalary()<0) throw new IllegalArgumentException(" 工作的工资不能小于0");
this.name=name;
//this.work=work;
this.work=new Work(work.getSalary());
}
public Work getWork(){
//return work;
return new Work(work.getSalary());
}
public String toString(){
return "name:"+name+" work:"+work;
}
}
在看看执行结果
name:taoge work:work.salary:3000
name:taoge work:work.salary:3000
哈,又一次防御成功。