Is there any way to instantiate a class without knowing its type until runtime and without using reflection?
It would seem that if all the classes I wish to instantiate extend the same abstract class or implement the same interface, this is a reasonable request. However, because you cannot enforce a constructor on those classes even if they开发者_运维知识库 do, I can't think of a way to do it.
No. Part of the reason for creating reflection in the first place was to make it so you could do things like instantiate a class at runtime without knowing its type in advance.
You sound like you're asking how to something like this where $CLASS is the name of a package defined at runtime:
eval {
require "$CLASS";
};
die $@ if $@;
$newObj = $CLASS->new();
Well, dude, that's why Sun added reflection...
The situation you described is unresolvable, but you may be looking for something like Factory pattern.
A Java service may provide what you are looking for. (See ServiceLoader javadoc too.)
I suppose if you know the names of the classes in advance, then you could use mock classes.
public class MySquareClass { public String methods ( ) { throw new RuntimeException ( ) ; }
public class MyCircleClass { ... stub methods ... }
...
You can use them in the code and the compiler will not know they are not "real implementations." Be sure to substitute the real implementions by runtime.
精彩评论