java class获取实例,如何从.class文件中获取java.lang.Class的实例?

My question is how to get an instance of java.lang.Class from a given .class file?

So if I have the file MyClass.class, and the corresponding java.io.File instance, how can I use this to get an instance of java.lang.Class that corresponds to MyClass?

解决方案

You actually need a classloader to do this (to turn a byte-code byte-stream into a class). There a few options here. One, you use a standard URLClassLoader instance, but that would rely on your being placed in a good java package location (you would create the URLClassLoader to the root of your file path in which you file resides. But this would only work when the directory structure mirrors the package structure of the class file you are trying to load).

The easiest base class would be SecureClassLoader as that allows you to run your code in a JVM with a security manager enabled (iow, you can set the code base)

The important method for you is the findClass as that would turn a binary name into a class (you can make your own mapping between the classname and the file your are loading). You can load the File and pass the bytes of the file to the most important method: defineClass. This is a method of the SecureClassLoader. It takes a binary name of your class, the ByteBuffer and a CodeSource (for Java Security)

To create a buffer from your file use:

FileInputStream fis = new FileInputStream(yourFileObj)

FileChannel channel = fis.getChannel();

ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, clsFile.length());

You need a CodeSource so you can use it in a secure environment, you might want to use something like:

CodeSource cs = new CodeSource(clsFile.getParent().toURI().toURL(), (CodeSigner[]) null);

and then invoke the

Class> aClass = super.defineClass(name, buffer, cs);

Hope this puts you into the right direction(!)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值