Modified the FieldSerializer to support classes with non-public no-arg constructors.

Finally we can end the tyranny of exposing dangerous public constructors in the
name of a cheap serialization.
experimental
Paul Speed 9 years ago
parent 69c17d72c8
commit 50b2f76bdf
  1. 26
      jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FieldSerializer.java

@ -34,6 +34,7 @@ package com.jme3.network.serializing.serializers;
import com.jme3.network.serializing.Serializer; import com.jme3.network.serializing.Serializer;
import com.jme3.network.serializing.SerializerException; import com.jme3.network.serializing.SerializerException;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.BufferOverflowException; import java.nio.BufferOverflowException;
@ -47,15 +48,31 @@ import java.util.*;
*/ */
public class FieldSerializer extends Serializer { public class FieldSerializer extends Serializer {
private static Map<Class, SavedField[]> savedFields = new HashMap<Class, SavedField[]>(); 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) { protected void checkClass(Class clazz) {
// See if the class has a public no-arg constructor // See if the class has a public no-arg constructor
try { 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 ) { } 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) { public void initialize(Class clazz) {
@ -121,7 +138,8 @@ public class FieldSerializer extends Serializer {
T object; T object;
try { try {
object = c.newInstance(); Constructor<T> ctor = (Constructor<T>)savedCtors.get(c);
object = ctor.newInstance();
} catch (Exception e) { } catch (Exception e) {
throw new SerializerException( "Error creating object of type:" + c, e ); throw new SerializerException( "Error creating object of type:" + c, e );
} }

Loading…
Cancel
Save