jni与序列化对象
System.out.println(FileContextCache.class); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(FileContextCache.class); byte[] data = baos.toByteArray(); int length = data.length; System.out.println(data); ByteArrayInputStream bais = new ByteArrayInputStream(data); ObjectInputStream ois = new ObjectInputStream(bais); Class d = (Class) ois.readObject(); System.out.println(d); System.out.println(d); FileContextCache dd = (FileContextCache)d.newInstance(); System.out.println(dd); System.out.println(dd); 通过 上面的代码可以发现,可以从一个byte[]数组中实例化一个java对象。 所以这个byte[]可以由jni来由C语言动态库生成,然后在java中再实例化这个对象. public class TTClassLoader extends ClassLoader { public Class loadClass() { //读取license.lic文件 InputStream in = TTClassLoader.class.getResourceAsStream("/person.data"); //可以从文件中得到字节数据,也可以由C++动态库得到 byte[] content = readFile(in); //defineClass由字节流在JVM中生成Class对象 return defineClass("com.Person", content, 0, content.length); } private static byte[] readFile(InputStream in) { byte[] fileContents = (byte[])null; int fileSize = 0; try { byte[] buffer = new byte[512]; for (int bytesRead = in.read(buffer); bytesRead != -1; bytesRead = in.read(buffer)) { byte[] newFileContents = new byte[fileSize + bytesRead]; if (fileSize > 0) { System.arraycopy(fileContents, 0, newFileContents, 0, fileSize); } System.arraycopy(buffer, 0, newFileContents, fileSize, bytesRead); fileContents = newFileContents; fileSize += bytesRead; } } catch (IOException e) { e.printStackTrace(); } //返回解密之后的文件内容 return encrypt(fileContents); } }
////////////////////////////////////////////////////////////////
public static <T extends Serializable> T cloneSerializedObject(T obj){
if(null == obj){
throw new NullPointerException();
}
T cloneObj = null;
ByteArrayOutputStream outputCache = null;
ObjectOutputStream oos = null;
ByteArrayInputStream inputCache = null;
ObjectInputStream ois = null;
try{
//在内存创建一个字节缓冲区(做为先把对象输出的目的地)
outputCache = new ByteArrayOutputStream();
//创建输出对象流,以字节缓冲区为输出目的地.
oos = new ObjectOutputStream(outputCache);
//输出对象到字节缓冲区.
oos.writeObject(obj);
//创建字节输入缓冲区,输入源为,存放对象数据的字节缓冲区.
inputCache = new ByteArrayInputStream(outputCache.toByteArray());
ois = new ObjectInputStream(inputCache);
//返回新对象,并做类型转换.
cloneObj = (T)ois.readObject();
}catch(Exception e){
//抛出包装后的异常。
throw new RuntimeException(e);
}finally{
//安全关闭所有流
try{
if(null != oos){
oos.close();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if(null != ois){
ois.close();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if (null != inputCache){
inputCache.close();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if (null != outputCache){
outputCache.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
return cloneObj;
}