Skip to content

Instantly share code, notes, and snippets.

@AndrewReitz
Last active January 3, 2016 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewReitz/8395652 to your computer and use it in GitHub Desktop.
Save AndrewReitz/8395652 to your computer and use it in GitHub Desktop.
Generic Types Example Problem (INCOMPLETE)
public class GenericsExampleProblem {
public static void main(String[] args) {
Class myClass = MyClass.class;
Method[] myClassMethods = myClass.getDeclaredMethods();
for (Method method : myClassMethods) {
// Skip any other methods
// This must be done this way instead of with getMethod(String Name, Class<?>... params) since
// we can not possibly know the params until at run time
if (!method.getName().equals("myMethod")) {
continue;
}
// Get the parameter for the myMethod
// This will be cast to class if it is overridden if not it will throw a class cast
// exception (interface was passed in) and you can assume that we are dealing with an
// object.
Class parameterType = (Class) method.getGenericParameterTypes()[0];
System.out.println(parameterType.toString());
// Output:
// class java.lang.String
// class java.lang.Object
// We get both the String and Object signatures
// If a type is passed with the generic you can never actually get that back,
// but there shouldn't really be a need to since you are dealing with code that should
// treating everything as an object at that point anyways
// I mean in general it's probably just easier to have the class type passed in and
// avoid doing this.
}
}
public interface MyInterface<E> {
public void myMethod(E item);
}
public static class MyClass implements MyInterface<String> {
@Override
public void myMethod(String item) {
System.out.println("myMethod");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment