Java可以通过继承父类并实现finalize,在父类构造器抛出异常后,通过将对象引用记录在一个静态域,使得需要被回收的对象保持存活并可以调用相应方法
现在存在一个被攻击的类,Attacked,在age小于18时,对象的构建会失败
public class Attacked { private int age; public Attacked(int age) { this.age = age; if (age < 18) { throw new InvalidParameterException("age must great than 18"); } } public void drink() { System.out.println("I can drink,because my age is: " + age); } }
通过添加一个攻击子对象
public class Attacker extends Attacked { static Attacked attacked; public Attacker(int age) { super(age); } @Override protected void finalize() throws Throwable { attacked = this; } }
调用下面方法
public static void main(String[] args) { try { new Attacker(10); } catch (Exception e) { } System.gc(); System.runFinalization(); attacked.drink(); }
可以看到,尽管age小于18,依然可以输出,从而得到错误的结果
I can drink,because my age is: 10