知识点温故

Java高阶知识点

2018-03-22  本文已影响8人  Echopppppp
**方法区(永久代):**永久代的回收有两种:常量池中的常量,无用的类信息,常量的回收很简单,没有引用了就可以被回收。对于无用的类进行回收,必须保证3点:

1. 类的所有实例都已经被回收
2. 加载类的ClassLoader已经被回收
3. 类对象的Class对象没有被引用(即没有通过反射引用该类的地方)

引用计数法(循环引用时失效)  标记-清除算法 标记-整理算法 copying算法 generation算法

ASCII 码 128位

GBK 《汉字内码扩展规范》

UTF-16 Unicode码 2字节定长编码

UTF-8 1~6字节变长编码

public class MyInvocationHandler implements InvocationHandler {
private String TAG = "MyInvocationHandler";
private Object obj;

public Object bind(Object obj){
    this.obj = obj;
    return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Log.d(TAG,"start"+method.getName());
    Object result = method.invoke(obj,args);
    Log.d(TAG,"end"+method.getName());
    return result;
}

}
```

```
 Human human = new HumanImp();
    ((TextView)findViewById(R.id.tv_content)).setText(((Human)new MyInvocationHandler().bind(human)).eat());
```

缺点: 
JDK的动态代理机制只能代理实现了接口的类,而不能实现接口的类就不能实现JDK的动态代理,cglib是针对类来实现代理的,他的原理是对指定的目标类生成一个子类,并覆盖其中方法实现增强,但因为采用的是继承,所以不能对final修饰的类进行代理。   

作用:1,方法增强,让你可以在不修改源码的情况下,增强一些方法,比如添加日志等。

2.以用作远程调用,好多rpc框架就是用代理方式实现的。

[参考文章](http://blog.csdn.net/fengyuzhengfan/article/details/49586277)

对象实现Serializable,不希望被序列化的属性加transient属性</br>
ObjectOutputStream & ObjectInputStream

   File aFile=new File("e:\\c.txt");
   Stu a=new Stu(1, "aa", "1");
   FileOutputStream fileOutputStream=null;
   try {
     fileOutputStream = new FileOutputStream(aFile);
     ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream);
     objectOutputStream.writeObject(a);
     objectOutputStream.flush();
     objectOutputStream.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }finally {
     if(fileOutputStream!=null)
     {
       try {
         fileOutputStream.close();
       } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }      
     }
   }
   FileInputStream fileInputStream=new FileInputStream(aFile);
   ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
   Stu s=(Stu)objectInputStream.readObject();
   System.out.println(s);
上一篇 下一篇

猜你喜欢

热点阅读