crm crm - 3 years ago 211
Java Question

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?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download