简体   繁体   中英

How can I use a Dynamically created class as Generics?

My problem is I do have a class that is created, compiled and initialized at runtime. I did this as writing the file as TestClass which is File f, then compile with:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
          compiler.run(null,null,null,f.getPath());

After that I load my class and use my methods etc. according to this example; http://viralpatel.net/blogs/java-dynamic-class-loading-java-reflection-api/

Now my problem is I need to do this:

MyTask<T> m = new MyTask<T>(0,0,0);

T should be my dynamically created class instead of Integer.class etc. However I couldn't find a way for it yet. If you do examine the example at the link I gave above, you will see I can have a instance of my class as in Object form and I can a Class instance for my dynamic class. However, whatever I tried I couldn't find the solution for this.

It keeps saying that Class myClass, can not be used as a type. So how can I use this dynamically created class as a type. Thank you very much.

There is no useful way to express in source code a type that does not exist at compile time. It would not anyway gain you anything more than using Object as a type parameter could do, because Java generics provide compile-time type checking, not run-time type checking.

It might be that your purposes could be served by creating an interface that your dynamic class will implement, and using the interface type as your type parameter.

You can't due to the fact that the generic type information is available only at compile time. When you create a class at runtime, there's no generic information available anywhere any more.

If your class implements an interface, you should use that as the type in code. Something along the lines of

MyInterface foo = myDynamicClass.newInstance();
someGenericMethod(foo);

public <T extends MyInterface> void someGenericMethod(T param) {}
// Or more likely, if there's no other classes that extend MyInterface
public void someGenericMethod(MyInterface param) {}

Of course it may not make any sense to even bother with generic type information, since it's used for static type checking and you're working with a dynamic class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM