简体   繁体   中英

How to get class reference by String name?

I am attempting to make the following method call dynamic:

JobDetail job = newJob(RunMeJob.class)
                  .withIdentity("myJob", "group1")
                  .build();

By doing the following:

private void scheduleJob(final SchedulerJob job, final SchedulerTrigger trigger) {

    final String fullyQualifiedName = "com.crm.scheduler.job.RunMeJob";//"com.crm.scheduler.job" + job.getImplementation();

    Class<?> cls = Class.forName(fullyQualifiedName, false, null);

    JobDetail jobDetail = newJob(cls)
              .withIdentity(job.getExternalReference(), trigger.getExternalReference())
              .build();
}

But I am receiving the following error:

The method newJob(Class< ? extends Job>) in the type JobBuilder is not applicable for the arguments (Class< capture#3-of ?>)

Here is the RunMeJob class:

package com.crm.scheduler.job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import com.crm.scheduler.task.RunMeTask;

@Component
public class RunMeJob implements Job {

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        new RunMeTask().printMe();
    }
}

How can I dynamically specify the class?

You have the right idea, basically, but you can't pass any old Class object to the newJob method - it must be a Class instance that represent a Job , and has to be specified as such in its generics:

Class<? extends Job> cls = 
    (Class<Job>) Class.forName(fullyQualifiedName, false, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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