Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.reflect.ParameterizedType;
- import java.lang.reflect.Type;
- import java.lang.reflect.TypeVariable;
- // http://stackoverflow.com/q/28143029/3080094
- public class ThingType {
- class ObjectThing<O> {}
- class NumberThing<N extends Number> extends ObjectThing<N> {}
- class IntegerThing extends NumberThing<Integer> {}
- public static void main(String[] args) {
- try {
- ThingType tt = new ThingType();
- tt.reflectThing(ObjectThing.class);
- tt.reflectThing(NumberThing.class);
- tt.reflectThing(IntegerThing.class);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- void reflectThing(Class<?> thingClass) {
- String classDecl = getClassDeclName(thingClass);
- System.out.println("Class: " + thingClass.getName());
- classDecl += reflectThingTypeVars(thingClass);
- Class<?> thingSuperClass = thingClass.getSuperclass();
- if (thingSuperClass != null && thingSuperClass != Object.class) {
- System.out.println("Super class: " + thingSuperClass.getName());
- classDecl = classDecl + " extends " + getClassDeclName(thingSuperClass);
- classDecl += reflectThingSuperTypeArgs(thingClass.getGenericSuperclass());
- }
- System.out.println("Source declaration: " + classDecl);
- System.out.println();
- }
- String getClassDeclName(Class<?> c) {
- String cname = c.getName().replace('$', '.');
- if (cname.indexOf('.') > 0) {
- cname = cname.substring(cname.lastIndexOf('.') + 1);
- }
- return cname;
- }
- String reflectThingTypeVars(Class<?> thingClass) {
- TypeVariable<?>[] typeVars = thingClass.getTypeParameters();
- if (typeVars.length == 0) {
- System.out.println("No type variables for " + thingClass);
- return "";
- }
- System.out.println("Typevar: " + typeVars[0] + " (of " + typeVars.length + ")");
- Type[] types = typeVars[0].getBounds();
- System.out.println("Type: " + types[0]+ " (of " + types.length + ")");
- String decl;
- if (types[0] == Object.class) {
- decl = typeVars[0].toString();
- } else {
- decl = typeVars[0].toString() + " extends " + getClassDeclName((Class<?>) types[0]);
- }
- return "<" + decl + ">";
- }
- String reflectThingSuperTypeArgs(Type genSuperClass) {
- String ta = "";
- if (genSuperClass instanceof ParameterizedType) {
- ParameterizedType genSuperPt = (ParameterizedType) genSuperClass;
- Type[] typeArgs = genSuperPt.getActualTypeArguments();
- System.out.println("Type arg: " + typeArgs[0] + " (of " + typeArgs.length + ")");
- if (typeArgs[0] instanceof Class<?>) {
- ta = getClassDeclName((Class<?>) typeArgs[0]);
- } else {
- ta = typeArgs[0].toString();
- }
- ta = "<" + ta + ">";
- }
- return ta;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment