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.
This commit is contained in:
parent
69c17d72c8
commit
50b2f76bdf
@ -34,6 +34,7 @@ package com.jme3.network.serializing.serializers;
|
||||
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 @@ import java.util.*;
|
||||
*/
|
||||
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 );
|
||||
//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 );
|
||||
}
|
||||
|
||||
public void initialize(Class clazz) {
|
||||
@ -121,7 +138,8 @@ public class FieldSerializer extends Serializer {
|
||||
|
||||
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 );
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user