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
?
You can't extend two or more classes at one time. Multiple inheritance is not allowed in java.
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.
Yes - it's possible (though not with your method signature) and yes, with your signature the types must be the same.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With