2

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);
}
Dokumans
  • 359
  • 1
  • 3
  • 14
  • Can you post a [mcve](http://stackoverflow.com/help/mcve)? –  Apr 27 '16 at 06:06
  • Show the code that you think should cause a compiler error. – Kayaman Apr 27 '16 at 06:17
  • i have edited the question and added the part where the jobs are added to the map. – Dokumans Apr 27 '16 at 06:23
  • 1
    http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – JB Nizet Apr 27 '16 at 06:27
  • change this line `Description d = new Description();` as `Description d = new Description();` you will achieve what you asked in your question. Because `Description d` is a raw type while `Description d ` is not a Raw Type. – Vikrant Kashyap Apr 27 '16 at 06:54
  • @VikrantKashyap this does not compile also for `JobB`, although`JobB` implements `IJob`. Compiler says "IJob" required, "JobB" found. – Dokumans Apr 27 '16 at 07:03

0 Answers0