I have following problem with Java generics and could not figure out how to solve it.
interface IJob {
void doJob();
}
This is how a job is described, it has a key and the class definition.
Later on in the code I want to create an object of the type Description.clazz
via reflection
class Description<T extends IJob> {
String key;
Class<T> clazz;
}
With this method I want to add jobs to my map.
To avoid runtime exceptions (ClassCastException
) I want to force that the passed description is implementing the interface IJob
.
Map<String, Description<IJob>> jobs;
public void addJob(Description<IJob> description)
{
jobs.put(description.key, description);
}
This are the jobs, and what I expected was that JobA
could not be add to my map because it does not implement IJob
, but it does. The compiler throws no error, and a simple unit test succeeds without an exception during runtime.
class JobA
{
}
class JobB implements IJob
{
@override
void doJob();
}
How should I define my Description
and the method addJob
to force a compiler error?
EDIT: This is an example how i am adding a job.
void addMyJobs()
{
Description d = new Description();
d.key = "A";
d.clazz = JobA.class; //why does this compile?
addJob(d);
d = new Description();
d.key = "B";
d.clazz = JobB.class;
addJob(d);
}