How to get actual type parameters used in generics implementation?


T

Todd

Hello,

I have determined that I have several classes that could be reduced to
a single generics class using type declarations. My issue arises from
other code using the class type to determine functionality. If I can
get the passed type declaration from the generic class, then I can
modify the other code to use the results of that query as opposed to a
direct getClass() call. A second benefit I would be able to reap from
getting the passed type is eliminating a possible user type-mismatch
error.

Here is the current class set-up (without methods) showing the generic
structure:

abstract public class ModificationPanel
<ModificationType,
ModificationPanelType extends Subpanel & ModifiableSubpanel>
{
}

public interface ModifiableSubpanel<ModificationType>
{
public ModificationType getModification();
}

abstract public class Subpanel extends JPanel
{
}

Now, here is a sample modification (called perturbation):

public class PerturbationSubpanel
extends Subpanel
implements ModifiableSubpanel<Perturbation>
{
}

public class PerturbationPanel
extends ModificationPanel<Perturbation, PerturbationSubpanel>
{
}

Since the PerturbationSubpanel uses the type Perturbation in the
implementation
of ModifiableSubpanel, if I could retrieve the type Perturbation, the
extension of
ModificationPanel by PerturbationPanel could just reference
PerturbationSubpanel
and I could get the Perturbation type internal to PerturbationPanel
(this is where
user type-mismatch would be eliminated).

When I tried getTypeParameters() what I got was ModificationType and
ModificationPanelType, not the desired Perturbation and
PerturbationPanel.

Is there a way to get the ModificationPanel to tell me what type(s)
have been
used when it is extended? Or more concisely, if the type can be
referenced,
ModificationPanel would no longer need to be abstract, so
PerturbationPanel
would not exist, but the type parameters would be used for later
differentiation.

Bottom line (question repeated for clarity):
Is there a way to get a generic class to return the actual type
parameters
used in declaration?

Thanks,
Toddd
 
Ad

Advertisements

S

Stefan Ram

Todd said:
Since the PerturbationSubpanel uses the type Perturbation in
the implementation of ModifiableSubpanel, if I could retrieve
the type Perturbation

class Perturbation{}
interface ModifiableSubpanel<T>{}
class PerturbationSubpanel implements ModifiableSubpanel<Perturbation>{}

public class Main
{ public static void main( final java.lang.String[] args )
{ java.lang.System.out.println
( ( ( java.lang.reflect.ParameterizedType )
PerturbationSubpanel.class.getGenericInterfaces()[ 0 ]).
getActualTypeArguments()[ 0 ]); }}

/*prints:

class Perturbation

*/
 

Top