Permalink
Browse files

Modified the FieldSerializer to support classes with non-public no-ar…

…g constructors.

Finally we can end the tyranny of exposing dangerous public constructors in the
name of a cheap serialization.
  • Loading branch information...
1 parent 69c17d7 commit 50b2f76bdfce2745c8a2ee7534484059dea70cd2 @pspeed42 pspeed42 committed Dec 24, 2015
@@ -34,6 +34,7 @@
import com.jme3.network.serializing.Serializer;
import com.jme3.network.serializing.SerializerException;
import java.io.IOException;
+import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.BufferOverflowException;
@@ -47,15 +48,31 @@
*/
public class FieldSerializer extends Serializer {
private static Map<Class, SavedField[]> savedFields = new HashMap<Class, SavedField[]>();
+ private static Map<Class, Constructor> savedCtors = new HashMap<Class, Constructor>();
protected void checkClass(Class clazz) {
// See if the class has a public no-arg constructor
try {
- clazz.getConstructor();
+ savedCtors.put(clazz, clazz.getConstructor());
+ return;
+ } catch( NoSuchMethodException e ) {
+ //throw new RuntimeException( "Registration error: no-argument constructor not found on:" + clazz );
+ }
+
+ // See if it has a non-public no-arg constructor
+ try {
+ Constructor ctor = clazz.getDeclaredConstructor();
+
+ // Make sure we can call it later.
+ ctor.setAccessible(true);
+
+ savedCtors.put(clazz, ctor);
+ return;
} catch( NoSuchMethodException e ) {
- throw new RuntimeException( "Registration error: no-argument constructor not found on:" + clazz );
- }
+ }
+
+ throw new RuntimeException( "Registration error: no-argument constructor not found on:" + clazz );
}
public void initialize(Class clazz) {
@@ -121,7 +138,8 @@ public int compare (SavedField o1, SavedField o2) {
T object;
try {
- object = c.newInstance();
+ Constructor<T> ctor = (Constructor<T>)savedCtors.get(c);
+ object = ctor.newInstance();
} catch (Exception e) {
throw new SerializerException( "Error creating object of type:" + c, e );
}

0 comments on commit 50b2f76

Please sign in to comment.