import java.io.Serializable;
public class Foo implements Serializable {
private String str;
public Foo(String str) {
this.str = str;
}
}
Foo是一个可以序列化的实体类
public class FooTest {
private static final ReflectionFactory REFLECTION_FACTORY = ReflectionFactory.getReflectionFactory();
public static void main(String[] args) {
Class<Foo> clazz = Foo.class;
try {
Foo foo = newSerializableInstance(clazz);
} catch (InvocationTargetException e) {
}
}
public static <T> T newSerializableInstance(Class<T> clazz) throws InvocationTargetException {
Class<?> cl = clazz;
while(Serializable.class.isAssignableFrom(cl)) {
if ((cl = cl.getSuperclass()) == null) {
return null;
}
}
try {
Constructor<?> cons = cl.getDeclaredConstructor((Class<?>[]) null);
cons = REFLECTION_FACTORY.newConstructorForSerialization(clazz, cons);
cons.setAccessible(true);
return (T)cons.newInstance();
} catch (NoSuchMethodException e) {
return null;
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
} catch (IllegalArgumentException e) {
return null;
}
}
}
有兴趣的可以参看JDK