使用包含参数的构造函数从类名创建Java对象
我想从名称创建类对象,调用构造函数并创建新实例。但我不知道如何向构造函数发送参数。我的基类是:使用包含参数的构造函数从类名创建Java对象,java,Java,我想从名称创建类对象,调用构造函数并创建新实例。但我不知道如何向构造函数发送参数。我的基类是: public carDao(ConnectionSource connectionSource, Class<Car> dataClass) throws SQLException { super(connectionSource, dataClass); } 我应该在getConstructor()中写什么?您需要为构造函数传递类 例如,如果构造函数有一个字符串参数
public carDao(ConnectionSource connectionSource, Class<Car> dataClass) throws SQLException
{
super(connectionSource, dataClass);
}
我应该在getConstructor()中写什么?您需要为构造函数传递类 例如,如果构造函数有一个字符串参数
Class myClass = Class.forName("carDao");
Constructor<?> cons = myClass.getConstructor(String.class);
Object o = cons.newInstance("MyString");
由于getConstructor方法声明如下:
//@param parameterTypes the parameter array
public Constructor<T> getConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
/@param参数键入参数数组
公共构造函数getConstructor(类…参数类型)
抛出NoSuchMethodException、SecurityException{
您应该将对象赋给getConstructor
方法,如下所示:
Class myClass = Class.forName("carDao");
Constructor intConstructor= myClass.getConstructor(ConnectionSource.class, Class.class);
Object o = intConstructor.newInstance(connectionSource, dataClass);
有关更多信息,请参阅:
公共构造函数getConstructor(类…参数类型)
抛出NoSuchMethodException,
安全例外
您需要在getConstructor
中传递类型或参数以获得正确的构造函数。请尝试
myClass.getConstructor(ConnectionSource.class,Class.class);
及
这应该起作用:
public static <T> T newInstance(final String className,final Object... args)
throws ClassNotFoundException,
NoSuchMethodException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
// Derive the parameter types from the parameters themselves.
Class[] types = new Class[args.length];
for ( int i = 0; i < types.length; i++ ) {
types[i] = args[i].getClass();
}
return (T) Class.forName(className).getConstructor(types).newInstance(args);
}
publicstatict newInstance(最终字符串类名、最终对象…args)
抛出ClassNotFoundException,
没有例外,
实例化异常,
非法访问例外,
IllegalArgumentException,
调用目标异常{
//从参数本身派生参数类型。
类[]类型=新类[args.length];
for(int i=0;i
这是否回答了您的问题-您应该首先解释为什么要使用反射,因为对于99%的问题,它是错误的解决方案。请尊重Java命名约定,并将类放入包中。DAO反模式,您不应该调用singleton。@RomanC您在哪里看到singleton?您介意接受answ吗呃?
public Constructor<T> getConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException,
SecurityException
myClass.getConstructor(ConnectionSource.class,Class.class);
intConstructor.newInstance(connectionSourceInstance, classInstance);
public static <T> T newInstance(final String className,final Object... args)
throws ClassNotFoundException,
NoSuchMethodException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
// Derive the parameter types from the parameters themselves.
Class[] types = new Class[args.length];
for ( int i = 0; i < types.length; i++ ) {
types[i] = args[i].getClass();
}
return (T) Class.forName(className).getConstructor(types).newInstance(args);
}