简体   繁体   中英

How can I determine amount of constructor parameters for a generic type using reflections in java?

I need to determine how many arguments a constructor accepts during runtime in a generic method. I know every type T extends the same baseclass and they only have one constructor each, but they take different amount of parameters.

public T someMethod() {
    // get amount of parameters T constructor takes
}

Is there a simple way of achieving this?

No. Due to type erasure , there is no way to find out anything about T from a method with that signature.

If you change the method to accept a type token , then yes:

public T someMethod(Class<T> clazz) {
    // eg:
    Constructor<?>[] constructors = clazz.getConstructors();
    // eg:
    constructors[i].getParameterTypes();
}

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