0

シグナリング プロトコルは、明確に定義された整数値を持つ列挙型を頻繁に使用します。例えば

public enum IpHdrProtocol {

TCP(6),
SCTP(132),
MPLS(137);
int Value;

IpProtocol(int value) {
    Value = value;
}

インスタンスの列挙型クラス型と整数値のみを使用して、そのような値を対応する列挙型に逆シリアル化する方法を見つけようとしています。

各列挙型に静的な getEnumFromInt(int) 関数を追加する必要がある場合、この「インターフェイス」を定義して、列挙型の作成者が列挙型を確実にシリアル化できるようにする方法を教えてください。

どうすればこれを行うことができますか?

4

3 に答える 3

1

どこまで行きたいかはわかりませんが、列挙型への侵襲を少なくするためのかなり醜いコードを次に示します。

public class Main {

    public enum IpHdrProtocol {

        TCP(6), SCTP(132), MPLS(137);
        int Value;

        IpHdrProtocol(int value) {
            Value = value;
        }
    }

    public static void main(String[] argv) throws NoSuchMethodException, IllegalArgumentException, InvocationTargetException,
            IllegalAccessException, SecurityException, NoSuchFieldException {
        System.err.println(getProtocol(6));
        System.err.println(getProtocol(132));
        System.err.println(getProtocol(137));
    }

    private static IpHdrProtocol getProtocol(int i) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
            SecurityException, NoSuchFieldException {
        Field f = IpHdrProtocol.class.getDeclaredField("Value");
        Method m = IpHdrProtocol.class.getMethod("values", null);
        Object[] invoke = (Object[]) m.invoke(null, null);
        for (Object o : invoke) {
            if (!f.isAccessible()) {
                f.setAccessible(true);
            }
            if (((Integer) f.get(o)).intValue() == i) {
                return (IpHdrProtocol) o;
            }
        }
        return null;
    }

    }
于 2012-03-07T12:19:27.283 に答える
1

Java の組み込みシリアライゼーションについて話している場合、Enum はすでに Serializable インターフェイスを実装しています。列挙値をシリアル化するだけで完了です。

独自のシリアライゼーションを構築したい場合は、int 値を読み書きし、これを enum に追加することでデシリアライズ時に対応する enum 値を取得できます。

public static IpHdrProtocol valueOf(int value) {
  for (IpHdrProtocol p : values()) {
    if (p.Value == value) return p;
  }
  return null; // or throw exception
}
于 2012-03-07T12:25:37.127 に答える
0

まず、コードがコンパイルされません。解決策は次のとおりです(これが必要な場合):

 public enum IpHdrProtocol {

    TCP(6),
    SCTP(132),
    MPLS(137);
    int Value;

    IpHdrProtocol(int value) {
        Value = value;
    }

    public static IpHdrProtocol getFromInt(int val) {
        for(IpHdrProtocol prot : values()) {
            if(prot.Value == val) {
                return prot;
            }
        }

        return null;
    }
}
于 2012-03-07T12:24:50.950 に答える