Reputation: 825
Quick question from anyone who knows java very well. My interpretation is that this is impossible because classes have to be explicitly declared before run-time but I want a direct answer.
Can I in some way do this (short code):
Class foo extends Object; //There is a class named foo.
public Vector<Object> classVector = new Vector<Object>();
public static void main(String[] args){
undefinedClassType = foo; //in some way
classVector.add(new undefinedClassType); //Vector now has a Object that can be casted to foo.
}
Just wondering. Thank you for all of the help and responses.
Upvotes: 2
Views: 149
Reputation: 1470
Use Java Reflection for that matter: https://docs.oracle.com/javase/tutorial/reflect/
You can compile a class at runtime using SDK tools and then load it into the Class loader, and then use reflection for instantiating it.
Use JavaCompiler for compiling classes at runtime.
Then, load it into your class loader using (the compiled class file needs to be in the classpath for it to be accessible to the class loader)
Class theClass = Class.forName("YourClass");
and finally use reflection for instantiating (this example is for a class with default constructor)
YourClass loadedClass = (YourClass)theClass.newInstance();
Upvotes: 1
Reputation: 599
The way to create an instance with an entirely new class during runtime is using Proxy.getProxy()
.
You need to give it an array of interfaces to implement and an invocation handler that will invoke the actual methods called via this class.
Note that the array if interfaces could be just Object
, but then you wouldn't be able to cast it into an instance whose methods are callable during compile time without reflection.
Upvotes: 1