0
protected <T> void myMethod(T obj, Class<?> type) 

I have seen this method signature and I don't understand why the type of the first argument explicitly passed as an argument. In fact I can get the type from obj.getClass();

protected <T> void myMethod(T obj) {
     Class type = obj.getClass();
} 

Is this just a design choice? Is there anything beneficial for doing the first method?

codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167

2 Answers2

0

The second implementation is actually the better one. In the first one, you might pass inconsistent parameters. E.g. you could pass an object of class A and pass integer as the second parameter. Therefore your code would be more vulnerable concerning typing errors.

avrFreak
  • 9
  • 1
0

One case I can think of

  • Instantiating a primitive array of a given type T, you cannot do this from the type parameter, you need the actual class.

Example

private static <T> void foo() {
    T[] bar = new T[1];  // <== not allowed
}

With a class parameter

private static <T> void bar(Class<T> clazz) {
    T[] bar = (T[]) Array.newInstance(clazz, 1);
}
Adam
  • 35,919
  • 9
  • 100
  • 137