2017-12-13 33 views
0

컨텍스트 :Runnable를 deserialize하는 방법이 있습니까?

그래서 텍스트 파일에 저장하려는 메서드 호출이 있습니다. 이 목적은 실행 가능한 직렬화 된 객체를 텍스트 파일에 저장하고 나중에 텍스트 파일에서 가져와 실행하는 것입니다.

final Runnable runnable =() -> { //Runnable object to serialize 
     client.publish("me/feed", GraphResponse.class, 
         Parameter.with("message", statusMessage)); 
}; 

final String gson = new Gson().toJson(runnable); // Serialized runnable as json. This works successfully. 

final Runnable x = new Gson().fromJson(gson, Runnable.class); // error 

오류는 다음과 같습니다

나는 오류를 이해
java.lang.RuntimeException: Unable to invoke no-args constructor for interface java.lang.Runnable. Registering an InstanceCreator with Gson for this type may fix this problem. 

는의 Runnable은 인터페이스이며 직렬화 할 수 없습니다. 그러나 내 문제를 해결할 수있는 다른 방법이 있습니까? 내가 당신에게 추천 할 수

해결 시도 1. ERROR

public class RunnableImplementation implements Runnable, Serializable { 

Runnable runnable; 

public RunnableImplementation() { 

} 

public RunnableImplementation(final Runnable runnable) { 
    this.runnable = runnable; 
} 

@Override 
public void run() { 
    runnable.run(); 
    } 
} 

public class ExampleClass { 

public static void main(String[] args) { 
    final Runnable runnable =() -> { 
     client.publish("me/feed", GraphResponse.class, 
       Parameter.with("message", statusMessage)); 
    }; 

    RunnableImplementation x = new RunnableImplementation(runnable); 

    String gson = new Gson().toJson(x); 
    RunnableImplementation runnableImplementation = new Gson().fromJson(gson, RunnableImplementation.class); // causes same error as above 
} 
} 
+0

yours client.publish에 의해 일반 텍스트로 저장해야 내 대체하거나 Java 또는 Protobuf 같은 바이너리 직렬화를 사용할 수 있습니까? –

+0

JSON에 직렬화하려고하십니까? 어떤 결과를 기대합니까? – shmosel

+0

인스턴트 메신저하지만 난 아무것도 사용하는 유연한 ObjectOutputStream/writeObject를 시도하고 그 같은 오류를 제공합니다 @AbhijitSarkar –

답변

-1

한 블라인드 시도는 실행 가능한 몇 가지 구현을 만들고 그것으로 코드를 시도하는 것입니다. 예를 들어 :

public class Main { 

    public static void main(String[] args) { 

     Runnable a = new A(); 

     String gson = new Gson().toJson(a); 
     Runnable runnable = new Gson().fromJson(gson, A.class); 

     runnable.run(); 
    } 

    public static class A implements Runnable{ 

     public void run() { 
      System.out.println("Here im"); 
     } 



    } 
} 

BTW System.out.println("Here im");

+0

예, 지금 시도하고 있습니다. 다른 해결책이 있는지 알고 싶었습니다. 가급적이면 '우아한' –

+0

시도했지만 실패했습니다. –

+0

누구든지 나를 빼먹었습니다. Jill 당신은 Runnable의 구현을 좀 지저분했다. 정확한 튜토리얼에 대한 내 게시물을 편집하는 방법 ... 만든 코드에 Runnable의 속성이 다시 포함되어 있습니다 ... – Majlanky