Vikrant Kashyap
Vikrant Kashyap

Reputation: 6886

Generic Method Definition contains <T extends Class> in-spite of return type is already Defined?

Can any body explain why <T extends Job> Typed-safe generics is used here ??

This code was written by one of my project team member who is no more part of the team. This looks like a strange Code for me. I just want to rewrite this and use it in another Code. Without deep Understanding i won't be able to change this.

    private <T extends Job> void addNewTask (Class<T> prm_objClassToSchedule, String prm_sJobName, String prm_sTriggerName, String prm_sCronExpression) throws ParseException, SchedulerException {
            CronTrigger v_objTrigger;
            JobDetail v_objJob;
            Scheduler v_objScheduler;
}

Upvotes: 2

Views: 649

Answers (3)

adranale
adranale

Reputation: 2874

As told in other answers T should extend Job, so the method could be clearly written like this:

private <T extends Job> void addNewTask (Class<T extends Job> prm_objClassToSchedule, String prm_sJobName, String prm_sTriggerName, String prm_sCronExpression) throws ParseException, SchedulerException {
            CronTrigger v_objTrigger;
            JobDetail v_objJob;
            Scheduler v_objScheduler;

The java compiler needs at least one mention to the exact type of the same generic type T to be able to compile it, no matter if this mention is in the parameter or in the return type. All the other mentions of T will be interpreted as the same class.

Upvotes: 3

OldCurmudgeon
OldCurmudgeon

Reputation: 65889

It is stating that the first parameter is a Class<T> wheref T extends Job.

class Job {

    public void go() {

    }
}

class X extends Job {
}

private <T extends Job> void addNewTask(Class<T> c) throws InstantiationException, IllegalAccessException {
    T t = c.newInstance();
    t.go();
}

public void test() throws InstantiationException, IllegalAccessException {
    Object o = new Object();
    Job j = new Job();
    X x = new X();
    // Not allowed because `o` is not a `Job`
    //addNewTask(o.getClass());
    // Both good.
    addNewTask(j.getClass());
    addNewTask(x.getClass());
}

Upvotes: 1

Edward Addley
Edward Addley

Reputation: 36

Without any context for which this method is used. I would say that the first parameter is expecting a Class type that extends from the Job class.

Upvotes: 1

Related Questions