2

From https://stackoverflow.com/a/1079799

Java is by design not fit for duck typing. The way you might choose to do it is reflection:

public void doSomething(Object obj) throws Exception {

    obj.getClass().getMethod("getName", new Class<?>[] {}).invoke(obj);
}

What does new Class<?>[] {} mean? Thanks.

1 Answers1

5

That creates an empty array of type Class<?> (which is a wild card capture of Classes). The array created is explicitly of length 0. Which indicates that getName takes no arguments (if it took arguments, the array would need to contain the appropriate classes to match the type signature).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Thanks. Could you explain what `{}` mean? –  Oct 02 '17 at 02:33
  • @Ben A zero length array initializer. `String[] arr = new String[] {"a"};` ... or `String[] arr = new String[] {};` (for an empty array) *or* `new String[0];` (for the same). – Elliott Frisch Oct 02 '17 at 02:34