com.adgear.anoa.AnoaReflectionUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of anoa-core Show documentation
Show all versions of anoa-core Show documentation
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.
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 extends SpecificRecord> 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 extends SpecificRecord>) 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 extends TBase,F>> 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 extends TFieldIdEnum, FieldMetaData> o1,
Map.Entry extends TFieldIdEnum, FieldMetaData> o2) {
return o1.getKey().getThriftFieldId() - o2.getKey().getThriftFieldId();
}
};
}