[b][color=red][size=medium]本文版权归作者所有,仅供用来网上学习来用,读者可以收藏,请不要下载到本机和重新发布到其它网站[/size][/color][/b]
有觉得可以改进的,请留言,也可加群讨论71326533
[b]工具类代码[/b]
[b]测试类:[/b]
[b]结果是:[/b]
abc
a
[b]不足之处:[/b]
对简单类型作为类的构造器的时候,会有异常,例如int。这是由于JDK的自动装包/拆包(Autoboxing/unboxing)造成的。它会把int转化过Integer,然后再去找构造器。这里只有用方法
public static <T> T createObject(Class<T> t, String className, Class<?>[] parameterTypes, Object[] initargs)
强行指定构造器参数类型来调用。int.class和Integer.class是不同的
有觉得可以改进的,请留言,也可加群讨论71326533
[b]工具类代码[/b]
import java.lang.reflect.Constructor;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClassUtil {
public static Logger log = Logger.getLogger(ClassUtil.class.getCanonicalName());
/**
* @param initargs If arguments count more than 1, all arguments can't be null and all arguments types must be references
*/
public static <T> T createObject(Class<T> t, String className, Object... initargs) {
if (initargs == null) {
return createObject(t, className, null, null);
}
Class<?>[] parameterTypes = new Class<?>[initargs.length];
for (int i = 0; i < initargs.length; i++) {
parameterTypes[i] = initargs[i].getClass();
}
return createObject(t, className, parameterTypes, initargs);
}
public static <T> T createObject(Class<T> t, String className, Class<?>[] parameterTypes, Object[] initargs) {
try {
Class<?> instanceClass = Class.forName(className);
if (parameterTypes != null && initargs != null) {
if (parameterTypes.length == initargs.length) {
Constructor<?> constructor = instanceClass.getConstructor(parameterTypes);
return t.cast(constructor.newInstance(initargs));
} else {
throw new IllegalArgumentException("Argument arrays lengths are not match");
}
} else if (parameterTypes == null && initargs == null) {
return t.cast(instanceClass.newInstance());
} else {
throw new IllegalArgumentException("Argument arrays must be both null or both not null");
}
} catch (Exception e) {
log.log(Level.SEVERE, CommonUtils.exceptionStack2String(e));
}
return null;
}
}
[b]测试类:[/b]
public class ClassUtilTest {
public static void main(String[] args) {
// 第一个参数为父类或父接口,第二个参数为类名,第三...个参数为构造器的参数,这里保证第三个及以后个参数不能为空。
// 这里用了范型,不用再强制转换了
CharSequence cs = ClassUtil.createObject(CharSequence.class, "java.lang.String", "abc");
System.out.println(cs);
System.out.println(cs.charAt(0));
}
}
[b]结果是:[/b]
abc
a
[b]不足之处:[/b]
对简单类型作为类的构造器的时候,会有异常,例如int。这是由于JDK的自动装包/拆包(Autoboxing/unboxing)造成的。它会把int转化过Integer,然后再去找构造器。这里只有用方法
public static <T> T createObject(Class<T> t, String className, Class<?>[] parameterTypes, Object[] initargs)
强行指定构造器参数类型来调用。int.class和Integer.class是不同的