2014-11-05 3 views
0

groovy에서 직렬화 가능 인터페이스 구현을 동적으로 생성하려고하는데,이 직렬화 인터페이스는 직렬화가 가능하고 args로 직렬화 될 수 있습니다. 지도를 사용하여 익명 인터페이스 구현을 만들었지 만 직렬화에 실패합니다. 그루비 폐쇄가 불가능 직렬화됩니다 경우에도 직렬화 복원 할 수 있도록 할 임의의 클래스 이름에 컴파일 된 경우클래스 정의가없는 Groovy 직렬화

gcloader = new ​GroovyClassLoade​r() 
script = "class X { public def x = [call: {y -> y+1}] as MyCallable }"​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 
gclass = gcloader.parseClass(script) 
x = gclass.newInstance().x​​ 
// serialzing x fails 

나는 확실하지 않다. 이것을 할 수있는 방법이 있습니까?

import groovy.lang.GroovyClassLoader 

def gcLoader = new GroovyClassLoader() 
def script = """ 
class X implements Serializable { 
    public def x = [ 
     call: { y -> y + 1 } 
    ] 
}""" 
def cls = gcLoader.parseClass(script) 
def inst = cls.newInstance().x 

def baos = new ByteArrayOutputStream() 
def oos = new ObjectOutputStream(baos) 

oos.writeObject(inst) 

def serialized = baos.toByteArray() 

def bais = new ByteArrayInputStream(serialized) 
def ois = new CustomObjectInputStream(bais, gcLoader) 
inst = ois.readObject() 

assert 2 == inst.call(1) 

public class CustomObjectInputStream extends ObjectInputStream { 
    private ClassLoader classLoader 

    public CustomObjectInputStream(InputStream ins, ClassLoader classLoader) throws IOException { 
     super(ins) 
     this.classLoader = classLoader 
    } 

    protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException { 
     return Class.forName(desc.getName(), false, classLoader) 
    } 
} 

는 기본적으로, 당신은 사용자 정의 ClassLoader으로 ObjectInputStream의 인스턴스가 필요합니다

+2

예외는 무엇입니까? –

+0

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SerializationUtils.html을 사용하고 이상하게도 java.io.NotSerializableException이 발생합니다 : X ie 최상위 클래스 : ( – FUD

+0

실제로 내가 "X 구현하는 경우 .."다음 직렬화 할 수 오전 deserialzing java.lang.ClassNotFoundException 얻을 : X $ _closure1 이해할 수 있습니다. 그래서 일부는 수행 할 수 있습니다. 다른 속임수? – FUD

답변

0

여기에 도움이 될 수있는 코드의 조각입니다.

+0

@Opal에게 감사드립니다. 그러나 이것이 내가 직렬화 된 개체를 전선 통해 보내려면? 다른 측면에서 클래스 로더 (직렬화에 대해 정의 된 클래스) (예 : 폐쇄) 않을 경우에도. – FUD

+0

정말 조사가 필요합니다. – Opal

0

필자가 제한적으로 연구 한 바에 따르면 jvm에는 python과 같은 코드를 피클 링할 수있는 표준/대중 라이브러리가 없다는 결론을 내렸다. URL 클래스 로더 등에서 몇 가지 방법이 있지만 몇 가지 고유 한 복잡성이 있습니다. 코드 문자열을 보내고 여러 컴퓨터에서 필요할 때마다 다시 컴파일하면됩니다.