Mark
Mark

Reputation: 3

Instantiate a class without knowing its type until runtime and without reflection

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.

Upvotes: 0

Views: 287

Answers (4)

emory
emory

Reputation: 10891

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.

Upvotes: 0

Brian Kent
Brian Kent

Reputation: 3854

A Java service may provide what you are looking for. (See ServiceLoader javadoc too.)

Upvotes: 0

Artsiom Anisimau
Artsiom Anisimau

Reputation: 1179

The situation you described is unresolvable, but you may be looking for something like Factory pattern.

Upvotes: 1

Mike Thomsen
Mike Thomsen

Reputation: 37506

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...

Upvotes: 1

Related Questions