jni与序列化对象

博客展示了Java代码,可从byte[]数组中实例化Java对象,且该byte[]可由JNI通过C语言动态库生成。还给出了自定义类加载器TTClassLoader的代码,能从文件或C++动态库获取字节数据,在JVM中生成Class对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值