- package java1.reflect;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Collection;
- import java.util.Properties;
- /**
- 编程写出一个内存泄露的例子。提示:用反射和IO知识。
- 所谓内存泄露就是说,这个对象我不要用了,但是它一直占用内存空间,
- 没有被释放(有个东西我不再用了,程序一直在运行,再也不用它了,结果它没有被释放掉,浪费内存)
- */
- public class Memory {
- public static void main(String args[]) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException{
- //IO操作
- InputStream in = Memory.class.getResourceAsStream("config.properties");
- System.out.println(in.available());
- Properties prop = new Properties();
- prop.load(in);
- in.close();
- String className = prop.getProperty("className");
- System.out.println(className);
- //反射
- Collection coll = (Collection)Class.forName(className).newInstance();
- Student st1 = new Student("zhangfei",23),
- st2 = new Student("zhangfei4",24),
- st3 = new Student("zhangfei6",26),
- st4 = new Student("zhangfei5",25);
- coll.add(st2);
- st2.setAge(400);
- coll.add(st3);
- coll.add(st1);
- coll.add(st4);
- //在这个地方造成了内存泄露,因为修改了与hashCode相关的属性,导致集合中涉及到st2的操作不能成功。
- System.out.println(coll.remove(st2));//返回结果为false
- }
- }
- class Student{
- private String name ;
- private int age;
- public Student(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- @Override
- public int hashCode() {
- return name.hashCode()+age*33;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
-
- }
复制代码 |