dimanche 5 novembre 2023

Why can't I use a lamda expression when calling Constructor.newInstance()?

I am trying to instantiate an object using Constructor.newInstance. The constructor requires one argument of type DoubleSupplier. This is successful if I first create a DoubleSupplier object, then pass the object to the newInstance method:

DoubleSupplier  supplier    = () -> 3.0;
obj = ctor.newInstance( supplier );

But if I try using the lamda directly in the newInstance invocation:

obj = ctor.newInstance( () -> 3.0 );

it fails to compile with "The target type of this expression must be a functional interface." What is the difference between the two methods?

Incidentally, I can use the lambda when instantiating an object using "new".

obj2 = new SubTypeA( () -> 3.0 );

Sample program follows.

public class CtorDemo
{
    public static void main(String[] args)
    {
        SuperType   obj = getSubType( SubTypeA.class );
        System.out.println( obj.getClass().getName() );
    }
    
    private static SuperType 
    getSubType( Class<? extends SuperType> clazz )
    {
        SuperType   obj = null;
        try
        {
            Constructor<? extends SuperType> ctor    =
                clazz.getConstructor( DoubleSupplier.class );
            
            DoubleSupplier  supplier    = () -> 3.0;
            obj = ctor.newInstance( supplier );
            // obj = ctor.newInstance( () -> 3.0 );
            // compile error
        }
        catch ( NoSuchMethodException
                | InvocationTargetException 
                | IllegalAccessException 
                | InstantiationException exc )
        {
            exc.printStackTrace();
            System.exit( 1 );
        }
        return obj;
    }

    private static class SuperType
    {
    }
    private static class SubTypeA extends SuperType
    {
        public SubTypeA( DoubleSupplier supplier )
        {
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire