Howe to correctly parameterise a Class

A

Adam Lipscombe

Folks


How do I correctly parameterise a Class?


I have code like this:

String classPath = "com.blah.bah.MyClass"
Class clazz = Class.forName(classPath);
Facade facade = (Facade) clazz.newInstance();


Facade is an interface and the class named by classPath will always implement this i/f.


Do I simply do: Class<Facade> clazz = Class.forName(classPath);


If not, what?



TIA - Adam
 
T

Thomas Fritsch

Adam said:
String classPath = "com.blah.bah.MyClass"
Class clazz = Class.forName(classPath);
Facade facade = (Facade) clazz.newInstance();


Facade is an interface and the class named by classPath will always
implement this i/f.


Do I simply do: Class<Facade> clazz = Class.forName(classPath);
Not quite.
If not, what?
You'll still need a cast:
Class<Facade> clazz = (Class<Facade>) Class.forName(classPath);
Facade facade = clazz.newInstance();
 
P

Piotr Kobzda

Thomas said:
Adam Lipscombe wrote:
[...]
If not, what?
You'll still need a cast:
Class<Facade> clazz = (Class<Facade>) Class.forName(classPath);
Facade facade = clazz.newInstance();

I prefer to use a bit type-safer version of the above:

Class<? extends Facade> clazz
= Class.forName(classPath).asSubclass(Facade.class);
Facade facade = clazz.newInstance();


piotr
 
T

Thomas Fritsch

Piotr said:
I prefer to use a bit type-safer version of the above:

Class<? extends Facade> clazz
= Class.forName(classPath).asSubclass(Facade.class);
Facade facade = clazz.newInstance();
Granted! I prefer yours, too.
 
D

Daniel Pitts

Piotr said:
Thomas said:
Adam Lipscombe wrote:
[...]
If not, what?
You'll still need a cast:
Class<Facade> clazz = (Class<Facade>) Class.forName(classPath);
Facade facade = clazz.newInstance();

I prefer to use a bit type-safer version of the above:

Class<? extends Facade> clazz
= Class.forName(classPath).asSubclass(Facade.class);
Facade facade = clazz.newInstance();


piotr
Not to mention that this is more correct.
The Class instance itself is the MyClass, not Facade, so Class<Facade>
is just plain wrong, where as Class<? extends Facade> is accurate.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top