38

The used method reference has return type Integer. But an incompatible String is allowed in the following example.

How to fix the method with declaration to get the method reference type safe without manually casting?

import java.util.function.Function;

public class MinimalExample {
  static public class Builder<T> {
    final Class<T> clazz;

    Builder(Class<T> clazz) {
      this.clazz = clazz;
    }

    static <T> Builder<T> of(Class<T> clazz) {
      return new Builder<T>(clazz);
    }

    <R> Builder<T> with(Function<T, R> getter, R returnValue) {
      return null; //TODO
    }

  }

  static public interface MyInterface {
    Integer getLength();
  }

  public static void main(String[] args) {
// missing compiletimecheck is inaceptable:
    Builder.of(MyInterface.class).with(MyInterface::getLength, "I am NOT an Integer");

// compile time error OK: 
    Builder.of(MyInterface.class).with((Function<MyInterface, Integer> )MyInterface::getLength, "I am NOT an Integer");
// The method with(Function<MinimalExample.MyInterface,R>, R) in the type MinimalExample.Builder<MinimalExample.MyInterface> is not applicable for the arguments (Function<MinimalExample.MyInterface,Integer>, String)
  }

}

USE CASE: a type safe but generic Builder.

I tried to implement a generic builder without annotation processing (autovalue) or compiler plugin (lombok)

import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

public class BuilderExample {
  static public class Builder<T> implements InvocationHandler {
    final Class<T> clazz;
    HashMap<Method, Object> methodReturnValues = new HashMap<>();

    Builder(Class<T> clazz) {
      this.clazz = clazz;
    }

    static <T> Builder<T> of(Class<T> clazz) {
      return new Builder<T>(clazz);
    }

    Builder<T> withMethod(Method method, Object returnValue) {
      Class<?> returnType = method.getReturnType();
      if (returnType.isPrimitive()) {
        if (returnValue == null) {
          throw new IllegalArgumentException("Primitive value cannot be null:" + method);
        } else {
          try {
            boolean isConvertable = getDefaultValue(returnType).getClass().isAssignableFrom(returnValue.getClass());
            if (!isConvertable) {
              throw new ClassCastException(returnValue.getClass() + " cannot be cast to " + returnType + " for " + method);
            }
          } catch (IllegalArgumentException | SecurityException e) {
            throw new RuntimeException(e);
          }
        }
      } else if (returnValue != null && !returnType.isAssignableFrom(returnValue.getClass())) {
        throw new ClassCastException(returnValue.getClass() + " cannot be cast to " + returnType + " for " + method);
      }
      Object previuos = methodReturnValues.put(method, returnValue);
      if (previuos != null) {
        throw new IllegalArgumentException("Value alread set for " + method);
      }
      return this;
    }

    static HashMap<Class, Object> defaultValues = new HashMap<>();

    private static <T> T getDefaultValue(Class<T> clazz) {
      if (clazz == null || !clazz.isPrimitive()) {
        return null;
      }
      @SuppressWarnings("unchecked")
      T cachedDefaultValue = (T) defaultValues.get(clazz);
      if (cachedDefaultValue != null) {
        return cachedDefaultValue;
      }
      @SuppressWarnings("unchecked")
      T defaultValue = (T) Array.get(Array.newInstance(clazz, 1), 0);
      defaultValues.put(clazz, defaultValue);
      return defaultValue;
    }

    public synchronized static <T> Method getMethod(Class<T> clazz, java.util.function.Function<T, ?> resolve) {
      AtomicReference<Method> methodReference = new AtomicReference<>();
      @SuppressWarnings("unchecked")
      T proxy = (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() {

        @Override
        public Object invoke(Object p, Method method, Object[] args) {

          Method oldMethod = methodReference.getAndSet(method);
          if (oldMethod != null) {
            throw new IllegalArgumentException("Method was already called " + oldMethod);
          }
          Class<?> returnType = method.getReturnType();
          return getDefaultValue(returnType);
        }
      });

      resolve.apply(proxy);
      Method method = methodReference.get();
      if (method == null) {
        throw new RuntimeException(new NoSuchMethodException());
      }
      return method;
    }

    // R will accep common type Object :-( // see https://stackoverflow.com/questions/58337639
    <R, V extends R> Builder<T> with(Function<T, R> getter, V returnValue) {
      Method method = getMethod(clazz, getter);
      return withMethod(method, returnValue);
    }

    //typesafe :-) but i dont want to avoid implementing all types
    Builder<T> withValue(Function<T, Long> getter, long returnValue) {
      return with(getter, returnValue);
    }

    Builder<T> withValue(Function<T, String> getter, String returnValue) {
      return with(getter, returnValue);
    }

    T build() {
      @SuppressWarnings("unchecked")
      T proxy = (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, this);
      return proxy;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
      Object returnValue = methodReturnValues.get(method);
      if (returnValue == null) {
        Class<?> returnType = method.getReturnType();
        return getDefaultValue(returnType);
      }
      return returnValue;
    }
  }

  static public interface MyInterface {
    String getName();

    long getLength();

    Long getNullLength();

    Long getFullLength();

    Number getNumber();
  }

  public static void main(String[] args) {
    MyInterface x = Builder.of(MyInterface.class).with(MyInterface::getName, "1").with(MyInterface::getLength, 1L).with(MyInterface::getNullLength, null).with(MyInterface::getFullLength, new Long(2)).with(MyInterface::getNumber, 3L).build();
    System.out.println("name:" + x.getName());
    System.out.println("length:" + x.getLength());
    System.out.println("nullLength:" + x.getNullLength());
    System.out.println("fullLength:" + x.getFullLength());
    System.out.println("number:" + x.getNumber());

    // java.lang.ClassCastException: class java.lang.String cannot be cast to long:
    // RuntimeException only :-(
    MyInterface y = Builder.of(MyInterface.class).with(MyInterface::getLength, "NOT A NUMBER").build();

    // java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
    // RuntimeException only :-(
    System.out.println("length:" + y.getLength());
  }

}
16
  • 1
    surprising behaviour. Out of interest: is it the same when you use a class instead of an interface for the builder?
    – GameDroids
    Commented Oct 11, 2019 at 9:02
  • Why is that unacceptable? In the first case, you don't give the type of the getLength, so it can be adjusted to return Object (or Serializable) to match the String parameter.
    – Thilo
    Commented Oct 11, 2019 at 9:14
  • 1
    I might be mistaken, but I think your method with is part of the problem as it returns null . When implementing the method with() by actually using the function's R type as the same R from the parameter you get the error. For example <R> R with(Function<T, R> getter, T input, R returnValue) { return getter.apply(input); }
    – GameDroids
    Commented Oct 11, 2019 at 9:20
  • 2
    jukzi, maybe you should provide code or an explanation about what your with method should actually do and why you need R to be Integer. For this, you need to show us how you want to utilize the return value. It seems that you want to implement some kind of builder-pattern, but I can not recognize a common pattern or your intention.
    – sfiss
    Commented Oct 11, 2019 at 11:38
  • 1
    Thanks. I also thought about checking for complete initialization. But since i see no way to do it at compile time i prefer to stick with the default values null/0. I have also no idea how to check for non interface methods at compile time. At runtime using an non interface like ".with(m -> 1).returning(1)" already results in an early java.lang.NoSuchMethodException
    – jukzi
    Commented Oct 11, 2019 at 12:48

4 Answers 4

27

In the first example, MyInterface::getLength and "I am NOT an Integer" helped to resolve the generic parameters T and R to MyInterface and Serializable & Comparable<? extends Serializable & Comparable<?>>respectively.

// it compiles since String is a Serializable
Function<MyInterface, Serializable> function = MyInterface::getLength;
Builder.of(MyInterface.class).with(function, "I am NOT an Integer");

MyInterface::getLength is not always a Function<MyInterface, Integer> unless you explicitly say so, which would lead to a compile-time error as the second example showed.

// it doesn't compile since String isn't an Integer
Function<MyInterface, Integer> function = MyInterface::getLength;
Builder.of(MyInterface.class).with(function, "I am NOT an Integer");
2
  • This answer fully answers the question why it is interpreted other then intendet. Interesting. Sounds like R is useless. Do you know any solution to the Problem?
    – jukzi
    Commented Oct 11, 2019 at 11:15
  • @jukzi (1) explicitly define method type parameters (here, R): Builder.of(MyInterface.class).<Integer>with(MyInterface::getLength, "I am NOT an Integer"); to make it not compile, or (2) let it gets resolved implicitly and hopefully proceed with no compile-time errors Commented Oct 11, 2019 at 11:21
11

Its the type inference that is playing its role here. Consider the generic R in the method signature:

<R> Builder<T> with(Function<T, R> getter, R returnValue)

In the case as listed:

Builder.of(MyInterface.class).with(MyInterface::getLength, "I am NOT an Integer");

the type of R is successfully inferred as

Serializable, Comparable<? extends Serializable & Comparable<?>>

and a String does imply by this type, hence the compilation succeeds.


To explicitly specify the type of R and find out the incompatibility, one can simply change the line of code as :

Builder.of(MyInterface.class).<Integer>with(MyInterface::getLength, "not valid");
2
  • Explicitly declaring R as <Integer> is interesting and fully answers the question why it goes wrong. However i am still searching for a solution without declaring the Type explicit. Any Idea?
    – jukzi
    Commented Oct 11, 2019 at 11:17
  • @jukzi What kind of solution are you looking for? The code already compiles, if you want to use it as it. An example of what you're looking for would be good to make things clear further.
    – Naman
    Commented Oct 11, 2019 at 11:39
11

It is because your generic type parameter R can be inferred to be Object, i.e. the following compiles:

Builder.of(MyInterface.class).with((Function<MyInterface, Object>) MyInterface::getLength, "I am NOT an Integer");
6
  • 1
    Exactly, if OP assigned the result of the method to a variable of type Integer, that would be where the compilation error happens.
    – sepp2k
    Commented Oct 11, 2019 at 9:09
  • @sepp2k Except that the Builder is only generic in T, but not in R. This Integer is just being ignored as far as type-checking the builder is concerned.
    – Thilo
    Commented Oct 11, 2019 at 9:19
  • 2
    R is inferred to be Object ... not really
    – Naman
    Commented Oct 11, 2019 at 9:23
  • @Thilo You're right, of course. I assumed the return type of with would use R. Of course that means there is no meaningful way to actually implement that method in a way that actually uses the arguments.
    – sepp2k
    Commented Oct 11, 2019 at 9:23
  • 1
    Naman, you are right , you and Andrew answered it in more detail with the correct inferred type. I just wanted to give a simpler explanation (although anyone looking at this question probably knows type inference and other types than just Object).
    – sfiss
    Commented Oct 11, 2019 at 9:29
0

This answer is based on the other answers which explain why it does not work as expected.

SOLUTION

The following code solves the problem by splitting the bifunction "with" into two fluent functions "with" and "returning":

class Builder<T> {
...
class BuilderMethod<R> {
  final Function<T, R> getter;

  BuilderMethod(Function<T, R> getter) {
    this.getter = getter;
  }

  Builder<T> returning(R returnValue) {
    return Builder.this.with(getter, returnValue);
  }
}

<R> BuilderMethod<R> with(Function<T, R> getter) {
  return new BuilderMethod<>(getter);
}
...
}

MyInterface z = Builder.of(MyInterface.class).with(MyInterface::getLength).returning(1L).with(MyInterface::getNullLength).returning(null).build();
System.out.println("length:" + z.getLength());

// YIPPIE COMPILATION ERRROR:
// The method returning(Long) in the type BuilderExample.Builder<BuilderExample.MyInterface>.BuilderMethod<Long> is not applicable for the arguments (String)
MyInterface zz = Builder.of(MyInterface.class).with(MyInterface::getLength).returning("NOT A NUMBER").build();
System.out.println("length:" + zz.getLength());

(is somewhat unfamiliar)

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.