簡體   English   中英

如何從非靜態接口方法實現 static 方法?

[英]How to achieve static method from non-static interface method?

我有一個這樣的界面:

public interface Byteable<T> {
    byte[] toBytes();
    T fromBytes(byte[] bytes);
}

顧名思義,它將 object 轉換為字節模式,並可以從給定的字節數組重新創建 object(如果不是,則拋出某種異常)。 我喜歡 toBytes() 方法,它必須是非靜態的,因為它只能應用於對象。 但是我怎樣才能創建一個 static 方法以便我可以調用

ClassName.fromBytes(...);

我如何確保實現該接口的每個 class 都具有這兩個功能,或者如何創建使用非靜態fromBytes(...)的 static 方法? 創建默認構造函數並執行類似的操作是一種好習慣嗎

new ClassName().fromBytes();

有什么好的做法嗎? 我想抽象的 class 也不是解決方案,因為它不能有 static 方法,可以嗎?

您可以創建一個抽象 class ,它將包含您的兩種方法作為抽象,您將在所需的 class 中擴展該抽象 class。

    public abstract class Byteable<T> {
      abstract byte[] toBytes();
      abstract T fromBytes(byte[] bytes); 
    }

   public YourClass extends Byteable<YourClass>{
     //provide implementation for abstract methods
     public byte[] toBytes(){
        //write your conversion code 
     }
     public YourClass fromBytes(byte[] bytes){
        //write your conversion code 
     }
   }

現在您可以創建 class 的 object 並使用這兩種方法。

YourClass obj = new YourClass();
obj.toBytes()
obj.fromBytes(....)

您可以對任何所需的 class 執行相同的操作,只需為 class 實現或賦予功能以執行這些任務。

除此之外,您可以編寫一個通用變換 class:

public class Byteable<I,O> {
  O toBytes(I obj){
    // Your transformation code
  }
  T fromBytes(O bytes){
    // Your implementation
  } 
}

Byteable<YourClass,byte[]> transformer = new Byteable<YourClass,byte[]>(); 
transformer.toBytes(new YourClass())
transformer.fromBytes(....);

我希望它對你有幫助。

您正在嘗試做的是一個抽象的 static 方法,這在 Java 中是不允許的。 檢查這個

除了這個問題,你可以嘗試這種方式。

public interface Byteable<T> {
    byte[] toBytes();
    Builder<T> builder();

    interface Builder<T> {
        T fromBytes(byte[] bytes);
    }
}

在這種情況下,您需要實現兩個interface 一個例子是這樣的。

public class Student implements Byteable<Student> {
    public final String name;

    public Student(String name) {
        this.name = name;
    }

    @Override
    public byte[] toBytes() {
        return name.getBytes();
    }

    @Override
    public Builder<Student> builder() {
        return bytes -> new Student(new String(bytes));
    }

    public static void main(String[] args) {
        Student s1 = new Student("Ana");
        Builder<Student> builder = s1.builder();
        byte[] bytes = s1.toBytes();
        Student s2 = builder.fromBytes(bytes);

        System.out.println(s2.name);    // Outputs Ana
    }
}

筆記:

有什么好的做法嗎? 我想抽象的 class 也不是解決方案,因為它不能有 static 方法,可以嗎?

您可以在抽象 class 中使用static方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM