objenesis是一个小型java类库用来实例化一个特定class的对象。
使用objenesis实例化对象
static class City {
private String code;
public City(String code) {
super();
this.code = code;
}
}
@Test
public void test02() {
Objenesis objenesis = new ObjenesisStd();
ObjectInstantiator<City> instantiator = objenesis.getInstantiatorOf(City.class);
City city = instantiator.newInstance();
System.out.println(city);
System.out.println(city.code);
}
执行结果
com.springframework.chapter34.App$City@726f3b58
null
使用JDK自带的Class实例化对象
@Test
public void test03() {
Class<City> clazz = City.class;
try {
City city = clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
执行结果
java.lang.InstantiationException: com.springframework.chapter34.App$City
at java.lang.Class.newInstance(Class.java:427)
at com.springframework.chapter34.App