简体   繁体   中英

scan .class files or jar file to reflection

In java project, I define a generic class

public class Test<T>

and a subclass

public class SubClass extends Test<Person> 

My question is how to scan code to find out which class is inherited from the Test, and the type T. As I know, the type T will be erased at runtime.

any method that we can do as that in .net(code as below)?

public static void RegisterVadas(Container container, params Assembly[] assemblies)
        {
            assemblies = assemblies.Distinct().ToArray();
            foreach (var assembly in assemblies)
            {
                foreach (var vada in assembly.GetTypes()
                .Where(t => t.IsOrHasGenericInterfaceTypeOf(typeof(IVada<>))))
                {
                    RegisterVada(container, vada);
                }
            }
        }

First, what do you want to achieve with this?

There are some solutions for this, such as using Guava's classpath scanner ; you can then find from the class what it's parent class is and what the type parameters are.

You can get the generics type information via reflection:

ParameterizedType superType = (ParameterizedType) SubClass.class.getGenericSuperclass();

The method allows you to access the type arguments by index. Test has only one type argument, so index == 0 in your case.

    /** Get the actual type argument used for a single generic placeholder */
    public <T> Class<T> getGenericType( int index ) {
        Object typeArg = superType.getActualTypeArguments()[ index ];
        if( typeArg instanceof Class ) {
            @SuppressWarnings( JavacWarnings.UNCHECKED )
            Class<T> result = (Class<T>) typeArg;
            return result;
        }

        if( typeArg instanceof ParameterizedType ) {
            ParameterizedType pt = (ParameterizedType) typeArg;
            @SuppressWarnings( JavacWarnings.UNCHECKED )
            Class<T> result = (Class<T>) pt.getRawType();
            return result;
        }

        throw new RuntimeException( "Unsupported type: " + typeArg.getClass() );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM