Java: How to check type definitions of a common class?

The idea is to define a base class that can call methods defined in derrived classes, but at creation time I want to make sure that such methods are defined exactly as required, that is, methods take only one argument, HashMap <String String>.

So far, I could verify with the following code that the method contains only one parameter and that it belongs to the HashMap class, but how can I verify that the general definition is <String, String>?

public boolean isMethodParameterValid(final Method method) {
  final Class<?>[] parameters = method.getParameterTypes();
  return ((parameters.length == 1) && parameters[0].isAssignableFrom(HashMap.class));
}
+5
source share
4 answers

, , / - , .

, , , . :

class Z
{
  public void f(List<String> lst) { }
}

...

Method m = Z.class.getMethod("f", List.class);
Type t = m.getGenericParameterTypes()[0];
if(t instanceof ParameterizedType) {
  ParameterizedType pt = (ParameterizedType) t;
  System.out.println("Generic params of first argument: " + Arrays.toString(pt.getActualTypeArguments()));
}    
+12

. Java "" , .. HashMap<String, String> HashMap . . .

+7

, . , , . , , .

+1

, .

Is there a reason why you can simply define an abstract method, as in a template template?

Then the check will be done statically.

protected abstract void process(HashMap<String, String>);

(is there also a reason why a HashMap is required only for the map?)

+1
source

All Articles