如何从.class文件中获取java.lang.Class的实例? [英] How to get an instance of java.lang.Class from a .class file?

查看:136
本文介绍了如何从.class文件中获取java.lang.Class的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何从给定的.class文件中获取java.lang.Class的实例?
那么,如果我有MyClass.class文件和相应的java.io.File实例,如何使用它来获取与MyClass对应的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?

推荐答案

实际上,您需要一个类加载器(将字节码字节流转换为类)。这里有一些选择。一种,您使用标准的 URLClassLoader 实例,但这将取决于您放置在良好的Java程序包位置中(您将创建 URLClassLoader 到文件所在文件路径的根目录。但这仅在目录结构镜像要加载的类文件的包结构时有效。

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).

最简单的基类是 SecureClassLoader ,因为它允许您在启用了安全管理器的JVM中运行代码(现在,您可以设置代码库)

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)

对您而言,重要的方法是 findClass ,因为它将二进制名称转换为类(您可以在类名和要加载的文件之间建立自己的映射)。您可以加载文件并将文件的字节传递给最重要的方法: defineClass 。这是 SecureClassLoader 的方法。它采用类的二进制名称,即 ByteBuffer CodeSource (用于Java安全性)

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

您需要 CodeSource 以便使用在安全的环境中,您可能需要使用类似的东西:

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

然后调用

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

希望这会使您朝正确的方向(!)

Hope this puts you into the right direction(!)

这篇关于如何从.class文件中获取java.lang.Class的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆