From 50b2f76bdfce2745c8a2ee7534484059dea70cd2 Mon Sep 17 00:00:00 2001 From: Paul Speed Date: Thu, 24 Dec 2015 03:29:36 -0500 Subject: [PATCH] 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. --- .../serializers/FieldSerializer.java | 26 ++++++++++++++++--- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FieldSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FieldSerializer.java index 0c6143073..ee8bffd88 100644 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FieldSerializer.java +++ b/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.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 savedFields = new HashMap(); + private static Map savedCtors = new HashMap(); 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 class FieldSerializer extends Serializer { T object; try { - object = c.newInstance(); + Constructor ctor = (Constructor)savedCtors.get(c); + object = ctor.newInstance(); } catch (Exception e) { throw new SerializerException( "Error creating object of type:" + c, e ); }