英文:
Create Object of new different Class every time
问题
我想连续创建一个新类的对象(具体是不同名称的类)。
public static void main(String args[]) {
while (true) {
Object obj = getNewClassObject();
System.out.println(obj.getClass().getName());
}
}
public static Object getNewClassObject() {
// 一些代码
}
任务是我们应该在这个方法中写什么,以便每次它返回一个不同类的对象,并且程序在每行打印不同的类名。
我已经尝试过使用匿名类、内部类、Lambda 等,但它们都返回相同的类名。
我当前的“简陋”解决方案是在一个具有重新加载能力的应用程序中创建新的类文件,然后使用反射库(或仅使用 Java 代码)来加载类并获取新类的对象。
但是这需要大量的内存,而且反射方法 getSubTypeOf()
耗时很长,大约 100 秒,而且经过一段时间后我会得到 OutOfMemoryError。
我希望有一种更好的方法来做这件事。我在考虑像卸载或释放类元数据以释放内存。
英文:
I want to create objects of a new class(different name specifically) continuously.
public static void main(String args[]) {
while (true) {
Object obj = getNewClassObject();
System.out.println(obj.getClass.getName());
}
}
public static Object getNewClassObject() {
// some code
}
The task is what should we write in the method so it returns an Object of different class every time and the program prints different class name in each line.
I have tried using Anonymous class, Inner class, lambdas etc.. but they all return the same class name.
My current "lame" solution is creating new class files inside a play application(has reloading ability) and then using reflection lib(or just java code) to load class and get the object of the new class.
But it takes a lot of memory also reflection method getSubTypeOf() takes a lot of time ~100 secs and after some time I get OutOfMemoryError.
I hope there is a better way to do it. I am thinking something like unloading or releasing class metadata to free up memory.
答案1
得分: 1
使用Javassist尝试
private static ClassPool pool = ClassPool.getDefault();
private static RandomString rs = new RandomString();
public static Object getNewClassObject() {
String name = rs.nextString();
Object obj = null;
try {
obj = pool.makeClass(name).toClass().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
return obj;
}
RandomString
来源于这里: https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
pom.xml
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.27.0-GA</version>
</dependency>
英文:
With Javassist try
private static ClassPool pool = ClassPool.getDefault();
private static RandomString rs = new RandomString();
public static Object getNewClassObject() {
String name = rs.nextString();
Object obj = null;
try {
obj = pool.makeClass(name).toClass().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
return obj;
}
RandomString
is from here: https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
pom.xml
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.27.0-GA</version>
</dependency>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论