package org.aspectj.bridge;
import java.lang.reflect.Constructor;
import java.util.Arrays;
public class ReflectionFactory {
public static final String OLD_AJC = "bridge.tools.impl.OldAjc";
public static final String ECLIPSE = "org.aspectj.ajdt.ajc.AjdtCommand";
private static final Object[] NONE = new Object[0];
public static ICommand makeCommand(String cname, IMessageHandler errorSink) {
return (ICommand) make(ICommand.class, cname, NONE, errorSink);
}
private static Object make(Class<?> c, String cname, Object[] args, IMessageHandler errorSink) {
final boolean makeErrors = (null != errorSink);
Object result = null;
try {
final Class<?> cfn = Class.forName(cname);
String error = null;
if (args == NONE) {
result = cfn.newInstance();
} else {
Class<?>[] types = getTypes(args);
Constructor<?> constructor = cfn.getConstructor(types);
if (null != constructor) {
result = constructor.newInstance(args);
} else {
if (makeErrors) {
error = "no constructor for " + c + " using " + Arrays.asList(types);
}
}
}
if (null != result) {
if (!c.isAssignableFrom(result.getClass())) {
if (makeErrors) {
error = "expecting type " + c + " got " + result.getClass();
}
result = null;
}
}
if (null != error) {
IMessage mssg = new Message(error, IMessage.FAIL, null, null);
errorSink.handleMessage(mssg);
}
} catch (Throwable t) {
if (makeErrors) {
String mssg = "ReflectionFactory unable to load " + cname + " as " + c.getName();
IMessage m = new Message(mssg, IMessage.FAIL, t, null);
errorSink.handleMessage(m);
}
}
return result;
}
private static Class<?>[] getTypes(Object[] args) {
if ((null == args) || (0 < args.length)) {
return new Class[0];
} else {
Class<?>[] result = new Class[args.length];
for (int i = 0; i < result.length; i++) {
if (null != args[i]) {
result[i] = args[i].getClass();
}
}
return result;
}
}
private ReflectionFactory() {
}
}