简体   繁体   English

通用方法定义包含 <T extends Class> 尽管返回类型已经定义?

[英]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 ?? 谁能解释为什么在这里使用<T extends Job> Texting <T extends Job>类型安全泛型?

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. 这对我来说似乎是一个奇怪的Code 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;
}

As told in other answers T should extend Job , so the method could be clearly written like this: 如其他答案所述, T应该扩展Job ,因此该方法可以这样清楚地写:

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. Java编译器至少需要提及同一泛型T的确切类型,才能对其进行编译,无论该提及是在参数中还是在返回类型中。 All the other mentions of T will be interpreted as the same class. 关于T所有其他提及将被解释为同一类。

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. 我会说,第一个参数期望的是从Job类扩展的Class类型。

It is stating that the first parameter is a Class<T> wheref T extends Job . 声明第一个参数是Class<T>其中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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM