在Java应用程序运行时定义类 [英] Defining a class while a Java application is running

查看:211
本文介绍了在Java应用程序运行时定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,是否可以在应用程序运行时动态创建类定义,然后创建该类的对象?

In Java, is it possible to create a class definition on the fly while an application is running, and then create an object of that class?

例如,正在运行的应用程序将读取一个文本文件,该文件包含要包含在新类中的类成员列表。然后,应用程序将根据成员列表定义类定义,然后对其进行实例化。

For example, a running application would read in a text file that contains a list of class members to include in the new class. The application would then define a class definition based on the list of members, and then insantiate it.

推荐答案

是的,可以这样做所以理论上你的类文件是字节代码,最后是一个字节数组!然后,您可以使用方法defineClass(String,byte [],int,int)来获取可用于通过反射实例化对象的Class实例。

Yes its possible to do so in theory your class file is byte code which is at the end a byte array! you can then use the method defineClass(String, byte[], int, int) to get a Class instance that can be used to instantiate objects via reflection.

在实践中,您可以使用 CGLib javaassist

In practice you can use something like CGLib or javaassist.

您还可以使用在文件中生成java代码,调用编译器,然后加载文件的漫长方法。

You can also use the long way of generating the java code in a file, invoking the compiler, then loading the file.

这篇关于在Java应用程序运行时定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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