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

com.adgear.anoa.AnoaReflectionUtils Maven / Gradle / Ivy

Go to download

Core classes for Anoa library, which aims to be a safe, convenient and fast record de/serialization wrapper for the Avro, Thrift and Jackson libraries, using the functional idioms of Java 8. The anoa-core module tries to keep upstream dependencies to a minimum.

There is a newer version: 3.1.2
Show newest version
package com.adgear.anoa;

import org.apache.avro.specific.SpecificRecord;
import org.apache.thrift.TBase;
import org.apache.thrift.TFieldIdEnum;
import org.apache.thrift.meta_data.FieldMetaData;

import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Utility class for properly-typed reflection methods.
 */
public class AnoaReflectionUtils {

  /**
   * @param className Avro SpecificRecord qualified class name
   */
  @SuppressWarnings("unchecked")
  static public Class getAvroClass(String className)
      throws ClassNotFoundException {
    if (className == null) {
      throw new ClassNotFoundException("Class name must not be null.");
    }
    Class recordClass = Class.forName(className);
    if (!SpecificRecord.class.isAssignableFrom(recordClass)) {
      throw new ClassCastException(className + " does not implement SpecificRecord.");
    }
    return (Class) recordClass;
  }

  /**
   * @param className Thrift qualified class name
   */
  @SuppressWarnings("unchecked")
  static public  Class getThriftClass(
      String className) throws ClassNotFoundException{
    if (className == null) {
      throw new ClassNotFoundException("Class name must not be null.");
    }
    Class recordClass = Class.forName(className);
    if (!TBase.class.isAssignableFrom(recordClass)) {
      throw new ClassCastException(className + " does not implement SpecificRecord.");
    }
    return (Class) recordClass;
  }

  /**
   * @param thriftClass the Thrift class
   * @param  Field enum type
   * @return An ordered map with field enum and field metadata for this class
   */
  @SuppressWarnings("unchecked")
  static public 
  LinkedHashMap getThriftMetaDataMap(Class> thriftClass) {
    LinkedHashMap result = new LinkedHashMap<>();
    ((Map) FieldMetaData.getStructMetaDataMap(thriftClass)).entrySet().stream()
        .sorted(comparator)
        .forEach(e -> result.put(e.getKey(), e.getValue()));
    return result;
  }

  static private Comparator> comparator
      = new Comparator>() {
    @Override
    public int compare(Map.Entry o1,
                       Map.Entry o2) {
      return o1.getKey().getThriftFieldId() - o2.getKey().getThriftFieldId();
    }
  };
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy