Unbound generic return type in Java

I play with some ideas about creating a Java API, and today I thought about this code for a while:

public <T> T getField1(Class<?> type, Class<T> retvalType, String fieldName) {
  Object retval = ...; // boring reflection code - value could be dog, could be duck
  return retvalType.cast(retval); // cast to expected - exception is raised here
}

// usage - we manually repeat the LHS type as a parameter
int foo = getField(o, Integer.class, "foo");

This is how I usually write the API, if not for the idea that the indication retvalTypegives me extra type safety. But does?

Since we have reflection, the type retval is unknown. Casting in the second line will reliably track type mismatch only when it retvalTypeis nonequivalent. On the other hand, even if we do not make this explicit cast, the Java runtime will generate a general result when it sets it to a variable - in other words, are there any flaws if we rewrite the above code as:

public <T> T getField2(Class<?> type, String fieldName) {
  return ...; // boring reflection code - the value type will be checked when we assign it
}

// usage - exception is raised at the next line if types don't match
int foo = getField(o, "foo");

, , . , ( ), , - , , , - .

- , ?


1:

, , , API.

, Date, long, , date.getTime(). , .

, , API . (Cue " ", " " ..).

+4
1

@shmosel , , , , LHS .

, :

class Foo<T> {
  void a1(Object o) {
    // forces to be explicit about the chance of heap polution
    @SuppressWarning("unchecked")
    Set<String> a = (Set<String>) getField1(o, Set.class, "foo");
    T c = (T) getField1(o, Set.class, "foo"); // guaranteed not to compile
  }

  void a2(Object o) {
    // implicit chance of heap polution in case of Set<Date>
    Set<String> a = (Set<String>) getField2(o, "foo");
    T c = getField2(o, "foo"); // will succeed even if foo is Date
  }
}

, getField(), , , Object ( ).

+1

Source: https://habr.com/ru/post/1673556/


All Articles