com.goikosoft.reflection.AssignableUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of reflection-utils Show documentation
Show all versions of reflection-utils Show documentation
Reflection utils. Simple envelope for reflection simplification
The newest version!
package com.goikosoft.reflection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Based on https://www.logicbig.com/how-to/code-snippets/jcode-reflection-is-assignable-from.html
* @author Dario
*
*/
public class AssignableUtils {
private static final Map, Class>> primitiveWrapperMap;
static {
Map, Class>> temp = new HashMap, Class>>();
temp.put(boolean.class, Boolean.class);
temp.put(byte.class, Byte.class);
temp.put(char.class, Character.class);
temp.put(double.class, Double.class);
temp.put(float.class, Float.class);
temp.put(int.class, Integer.class);
temp.put(long.class, Long.class);
temp.put(short.class, Short.class);
primitiveWrapperMap = Collections.unmodifiableMap(temp);
}
/**
* Tests if from is assignable to to
*
* @param to destination class
* @param from source class
* @return true is from is assignable to to
* @throws NullPointerException if to or from are null
* @see Class#isAssignableFrom(Class)
*/
public static boolean isAssignableFrom(Class> to, Class> from) throws NullPointerException {
if (to.isAssignableFrom(from)) {
return true;
}
if (from.isPrimitive()) {
return isPrimitiveWrapperOf(to, from);
}
if (to.isPrimitive()) {
return isPrimitiveWrapperOf(from, to);
}
return false;
}
/**
* Checks if the given target class is a primitive wrapper of the provided primitive.
*
* @param targetClass class to test
* @param primitive primitive to test
* @return true if targetClass is a primitive wrapper of primitive
* @throws IllegalArgumentException IF primitive is not a primitive
* @throws NullPointerException IF primitive is null or targetClass is null
*/
public static boolean isPrimitiveWrapperOf(Class> targetClass, Class> primitive) throws IllegalArgumentException, NullPointerException{
if (!primitive.isPrimitive()) {
throw new IllegalArgumentException("First argument has to be primitive type");
}
return targetClass.equals(primitiveWrapperMap.get(primitive));
}
/**
* Checks if class1 and class2 are a primitive and it's wrapper. The order does not matter.
*
* @param class1 a class
* @param class2 another class
* @return true if class1 is a primitive wrapper of class2 or vice-versa
* @throws NullPointerException If class1 is null or class2 is null
* @see #isPrimitiveWrapperOf(Class, Class)
*/
public static boolean isPrimitiveAndWrapper(Class> class1, Class> class2) throws NullPointerException {
if (class1.isPrimitive()) {
return isPrimitiveWrapperOf(class2, class1);
}
if (class2.isPrimitive()) {
return isPrimitiveWrapperOf(class1, class2);
}
return false;
}
}