java 对象转换与匿名内部类
一、对象操作1.序列化与反序列化
private Blob msg; private Serializable serialiableMsg;public Serializable getSerialiableMsg() throws SQLException { InputStream is = getMsg().getBinaryStream(); serialiableMsg = (is == null) ? null : (Serializable) SerializationUtils.serialize(is); return serialiableMsg; } public void setSerialiableMsg(Serializable serialiableMsg) { this.serialiableMsg = serialiableMsg; byte[] b = SerializationUtils.deserialize(serialiableMsg); setMsg(b == null ? null : Hibernate.createBlob(b)); }
2.对象转换
ByteArrayOutputStream bs = new ByteArrayOutputStream();ObjectOutputStream os = new ObjectOutputStream(bs); os.writeObject(msg);//把对象写到os里。byte[] b = bs.toByteArray();//通过bs获得转变后的byte数组。mss.setMsg(b);ByteArrayInputStream bi = new ByteArrayInputStream(mss.getMsg()); ObjectInputStream oi;Serializable msg=null;oi = new ObjectInputStream(bi);msg = (Serializable)oi.readObject();
/* * 复制对象obj,类似于值传递,非引用 */ private Object cloneObject(Object obj) throws Exception{ByteArrayOutputStreambyteOut = new ByteArrayOutputStream();ObjectOutputStream out = new ObjectOutputStream(byteOut);out.writeObject(obj); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());ObjectInputStream in =new ObjectInputStream(byteIn); return in.readObject(); }
二、java anonymous inner class
1.interface
public interface Animal { void sound();}
2.实例
//匿名内部类new <类或接口> <类的主体>public class JAnonymousInnerClass { //定义一个内部类class Cat{private String type;private String color;public void sound(){ System.out.println(color + " "+ type + "is shouting...");}public void setType(String type){this.type = type;}public void setColor(String color){this.color = color;}}/** * 定义一个匿名内部类:new class方式 * @param _type * @param _color * @return */public Cat get(final String _type,final String _color){return new Cat(){//new Class{//初始化块setType(_type);setColor(_color);}public String toString(){return _color.concat(" ").concat(_type);}};}/** * 定义一个匿名内部类:new interface方式 * @param _type * @return */public Animal get(final String _type){return new Animal(){//new Interfaceprivate String type = _type; public void sound(){ System.out.println(type + "is shouting..."); } public String toString(){return type;}};//注意分号}public static void main(String[] args){JAnonymousInnerClass jaic = new JAnonymousInnerClass();jaic.get("panda").sound();jaic.get("cat", "black").sound();}}
3.实现回调
public interface CallBack {void execute();}
public void testRunTime(CallBack callBack) { long begin = System.currentTimeMillis(); callBack.execute(); long end = System.currentTimeMillis(); System.out.println(":" + (end - begin)); } public void testCallback(){testRunTime(new CallBack(){//匿名内部类public void execute() {try {Thread.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}};});}
页:
[1]