使用Class生成实例 和 构造方法生成实例
import com.pss.model.ReflectionModel;
import java.lang.reflect.Constructor;
public class ReflectionTest2 {
public static void main(String[] args) throws Exception {
// 获取Class
Class<ReflectionModel> clazz3 = ReflectionModel.class;
// 生成实例
ReflectionModel model = clazz3.newInstance();
System.out.println(model);
// 通过构造方法生成实例
Constructor<?>[] constructors = clazz3.getConstructors();
// 构造方法1
ReflectionModel model1 = (ReflectionModel) constructors[0].newInstance("c1", 1);
System.out.println(model1);
// 构造方法2
ReflectionModel model2 = (ReflectionModel) constructors[1].newInstance("c2");
System.out.println(model2);
// 构造方法3
ReflectionModel model3 = (ReflectionModel) constructors[2].newInstance();
System.out.println(model3);
}
}
打印结果:
调用构造方法1
ReflectionModel{sql='null', count=null}
调用构造方法3
ReflectionModel{sql='c1', count=1}
调用构造方法2
ReflectionModel{sql='c2', count=null}
调用构造方法1
ReflectionModel{sql='null', count=null}
如果要获取非public构造方法,要使用
// public构造方法
System.out.println(clazz3.getConstructors().length);
// 包含非public构造方法
System.out.println(clazz3.getDeclaredConstructors().length);
获取指定构造方法生成实例
Constructor<? extends ReflectionModel> constructor = clazz3.getConstructor(String.class, Integer.class);
ReflectionModel model4 = constructor.newInstance("c1", 1);
System.out.println(model4);