Class of subclass as parameter

P

Peter Ashford

Hi There,

I have a class which maps a name to a class like so:

class Mapping {
private String name;
private Class runner;

public Mapping(String name, Class runnerClass){
m_name = name;
m_runner = runnerClass;
}
}

What I want to be able to do is to change that so the runnerClass can
be defined as only being the Class object of a Class which extends a
specific class ("EditorRunner" in this case).

Something like this compiles, but doesn't give the required results:


class Mapping {
private String name;
private Class<EditorRunner> runner;

public Mapping(String name, Class<EditorRunner> runnerClass){

m_name = name;
m_runner = runnerClass;
}
}

With this latter code, it works for EditorRunner.class as a parameter
but not for the .class member of any subclass of EditorRunner.

Anyone know how I can get the desired effect?

Cheers,

Peter.
 
M

Michael Rauscher

Peter said:
class Mapping {
private String name;
private Class<EditorRunner> runner;

public Mapping(String name, Class<EditorRunner> runnerClass){

m_name = name;
m_runner = runnerClass;
}
}

With this latter code, it works for EditorRunner.class as a parameter
but not for the .class member of any subclass of EditorRunner.

Anyone know how I can get the desired effect?

Use <? extends EditorRunner>.

To be more generic (I replaced runner because to me it's
indistinguishable how a "Mapping" is related to a "runner")

class Mapping<T> {
private String name;
private Class<? extends T> clazz;

public Mapping( String name, Class<? extends T> clazz ) {
this.name = name;
this.clazz = clazz;
}
}

Bye
Michael
 
R

Robert Klemme

Michael said:
Use <? extends EditorRunner>.

To be more generic (I replaced runner because to me it's
indistinguishable how a "Mapping" is related to a "runner")

class Mapping<T> {
private String name;
private Class<? extends T> clazz;

public Mapping( String name, Class<? extends T> clazz ) {
this.name = name;
this.clazz = clazz;
}
}

I'd probably also consider to make Mapping the complete mapping (i.e.
all name - class pairs). Depending on the OP's problem to solve that
might or might not be more useful.

Kind regards

robert
 

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,266
Messages
2,571,079
Members
48,772
Latest member
Backspace Studios

Latest Threads

Top