diff --git a/core/src/main/java/org/jboss/jandex/Type.java b/core/src/main/java/org/jboss/jandex/Type.java index 992aef40..81c361b1 100644 --- a/core/src/main/java/org/jboss/jandex/Type.java +++ b/core/src/main/java/org/jboss/jandex/Type.java @@ -198,6 +198,56 @@ public static Type create(DotName name, Kind kind) { } } + /** + * Creates a type that corresponds to the given {@code clazz}. The resulting type may be: + * + * + * @param clazz a {@link Class} + * @return a {@link Type} corresponding to the given {@code clazz} + */ + public static Type create(Class clazz) { + if (clazz.isArray()) { + int dimensions = 1; + Class componentType = clazz.getComponentType(); + while (componentType.isArray()) { + dimensions++; + componentType = componentType.getComponentType(); + } + return ArrayType.create(create(componentType), dimensions); + } + + if (clazz.isPrimitive()) { + if (clazz == Void.TYPE) { + return VoidType.VOID; + } else if (clazz == Boolean.TYPE) { + return PrimitiveType.BOOLEAN; + } else if (clazz == Byte.TYPE) { + return PrimitiveType.BYTE; + } else if (clazz == Short.TYPE) { + return PrimitiveType.SHORT; + } else if (clazz == Integer.TYPE) { + return PrimitiveType.INT; + } else if (clazz == Long.TYPE) { + return PrimitiveType.LONG; + } else if (clazz == Float.TYPE) { + return PrimitiveType.FLOAT; + } else if (clazz == Double.TYPE) { + return PrimitiveType.DOUBLE; + } else if (clazz == Character.TYPE) { + return PrimitiveType.CHAR; + } else { + throw new IllegalArgumentException("Unknown primitive type " + clazz); + } + } + + return ClassType.create(DotName.createSimple(clazz.getName())); + } + /** * Creates an instance of specified type with given type {@code annotations}. * To create the type instance, this method delegates to {@link #create(DotName, Kind)}. diff --git a/core/src/test/java/org/jboss/jandex/test/TypeFromClassTest.java b/core/src/test/java/org/jboss/jandex/test/TypeFromClassTest.java new file mode 100644 index 00000000..4fe9e14b --- /dev/null +++ b/core/src/test/java/org/jboss/jandex/test/TypeFromClassTest.java @@ -0,0 +1,31 @@ +package org.jboss.jandex.test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.jboss.jandex.ArrayType; +import org.jboss.jandex.ClassType; +import org.jboss.jandex.DotName; +import org.jboss.jandex.PrimitiveType; +import org.jboss.jandex.Type; +import org.jboss.jandex.VoidType; +import org.junit.jupiter.api.Test; + +public class TypeFromClassTest { + @Test + public void test() { + Type type = Type.create(void.class); + assertEquals(VoidType.VOID, type); + + type = Type.create(byte.class); + assertEquals(PrimitiveType.BYTE, type); + + type = Type.create(Object.class); + assertEquals(ClassType.create(DotName.OBJECT_NAME), type); + + type = Type.create(boolean[].class); + assertEquals(ArrayType.create(PrimitiveType.BOOLEAN, 1), type); + + type = Type.create(String[][].class); + assertEquals(ArrayType.create(ClassType.create(DotName.STRING_NAME), 2), type); + } +}