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

net.dongliu.prettypb.runtime.utils.ProtoUtils Maven / Gradle / Ivy

There is a newer version: 0.3.5
Show newest version
package net.dongliu.prettypb.runtime.utils;

import net.dongliu.prettypb.runtime.include.ProtoType;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.NoSuchElementException;

/**
 * @author Dong Liu
 */
public class ProtoUtils {

    public static boolean isPrimitive(ProtoType type) {
        switch (type) {
            case Int32:
            case UInt32:
            case SInt32:
            case Int64:
            case UInt64:
            case SInt64:
            case Double:
            case Float:
            case Fixed32:
            case SFixed32:
            case Fixed64:
            case SFixed64:
            case Bool:
                return true;
            default:
                return false;
        }
    }

    /**
     * get enum int value field
     *
     * @param value
     * @param 
     * @return
     */
    public static  int getEnumValue(T value) {
        Method method;
        try {
            method = value.getClass().getMethod("getValue");
            return (Integer) method.invoke(value);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            // should not happen in generated code
            throw new RuntimeException(e);
        }
    }

    /**
     * from int value get enum. we assume enum get a method named parse accepted int parameter
     *
     * @param clazz
     * @param value
     * @param 
     * @return
     */
    public static  T parseEnum(Class clazz, int value) {
        try {
            Method method = clazz.getMethod("valueOf", int.class);
            return (T) method.invoke(null, value);
        } catch (NoSuchElementException | InvocationTargetException | NoSuchMethodException |
                IllegalAccessException e) {
            // should not happen in generated code
            throw new RuntimeException(e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy