All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.redkalex.convert.pson.ProtobufEnumSimpledCoder Maven / Gradle / Ivy

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkalex.convert.pson;

import java.lang.reflect.Method;
import java.util.*;
import org.redkale.convert.*;

/**
 * 枚举 的SimpledCoder实现
 *
 * 

* 详情见: https://redkale.org * * @author zhangjx * @param Reader输入的子类型 * @param Writer输出的子类型 * @param Enum的子类 */ public class ProtobufEnumSimpledCoder extends SimpledCoder { private final Class type; private final Map values1 = new HashMap<>(); private final Map values2 = new HashMap<>(); public ProtobufEnumSimpledCoder(Class type) { this.type = type; try { final Method method = type.getMethod("values"); int index = -1; for (E item : (E[]) method.invoke(null)) { values1.put(item, ++index); values2.put(index, item); } } catch (Exception e) { throw new RuntimeException(e); } } @Override public void convertTo(final W out, final E value) { if (value == null) { out.writeNull(); } else { ((ProtobufWriter)out).writeUInt32(values1.getOrDefault(value, -1)); } } @Override @SuppressWarnings("unchecked") public E convertFrom(final R in) { int value = ((ProtobufReader)in).readRawVarint32(); if (value == -1) return null; return values2.get(value); } @Override public Class getType() { return type; } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy