public class ConstructorTest {
@Test @SuppressWarnings(“unchecked”)
public void testConstructor(){
try {
Class clazz = Class.forName(“cn.vicky.utils.User”);
Method method = clazz.getDeclaredMethod(“getName”);
Constructor<? extends Live> constructor = clazz.getConstructor(String.class);
System.out.println(method.invoke(constructor.newInstance(“Vicky”)));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
abstract class Live{
String name;
public Live(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class User extends Live{
public User(String name) {
super(name);
}
public String getName() {
return ” —> ” +name;
}
}
打印:
—> Vicky
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.logging.Logger;
import cn.vicky.service.command.BaseCommand;
import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.ManagedReference;
import com.sun.sgs.app.Task;
public class SolutionCommandTask implements Task, Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(SolutionCommandTask.class.getName());
private String className;
private String functionName;
private Map mapMessage;
private String username;
private ManagedReference<Task[]> tasksRef;
public SolutionCommandTask(String className, String functionName, Map mapMessage, String username,
Task… tasks) {
super();
this.className = className;
this.functionName = functionName;
this.mapMessage = mapMessage;
this.username = username;
if (tasks.length > 0)
this.tasksRef = AppContext.getDataManager().createReference(tasks);
}
public void run() throws Exception {
long time1 = System.currentTimeMillis();
try {
Class clazz = Class.forName(className);
Constructor<? extends BaseCommand> command;
Method method = clazz.getMethod(functionName);
// Method method = clazz.getDeclaredMethod(functionName);
if (tasksRef == null) {
command = clazz.getConstructor(Map.class, String.class);
method.invoke(command.newInstance(mapMessage, username));
} else {
command = clazz.getConstructor(Map.class, String.class, Task[].class);
method.invoke(command.newInstance(mapMessage, username, tasksRef.get()));
}
} catch (Exception e) {
e.printStackTrace();
logger.warning(“ReceivedMessageTask –> run –> ” + e.getMessage());
}
long time2 = System.currentTimeMillis();
System.out.println(“SolutionCommandTask run() 耗时 : ” + (time2 – time1));
}
}