Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend the generic type to multiple classes in Java?

Tags:

java

generics

I am trying to write a method in Java that uses a generic parameter and which I want to restrict to being exclusively either one of three possible classes (either Field, Method, or Constructor).

I've tried the following header:

private static <T extends Field,Method,Constructor> T[] sort(T[] anArray)

But this way it ignores generic parameters of type Method or Constructor. Using the following also produces an error:

private static <T extends Field | Method | Constructor> T[] sort(T[] anArray)

Is it possible to do such a thing in Java?

like image 420
programmar Avatar asked Oct 14 '15 08:10

programmar


People also ask

Can you extend multiple classes in Java?

You can't extend two or more classes at one time. Multiple inheritance is not allowed in java.

Can a generic class be extended?

We can add generic type parameters to class methods, static methods, and interfaces. Generic classes can be extended to create subclasses of them, which are also generic. Likewise, interfaces can also be extended.

Can a generic class have multiple generic parameters Java?

Yes - it's possible (though not with your method signature) and yes, with your signature the types must be the same.


1 Answers

For your particular case (If you are talking about the Reflection specific classes), you are in luck.

You can use the AccessibleObject class.

private static <T extends AccessibleObject> T[] sort(T[] anArray)

You may also be interested in Member interface depending on your requirement.

like image 168
Codebender Avatar answered Nov 15 '22 03:11

Codebender