我的问题不容易用单词来解释,幸运的是,展示起来也不是那么困难。所以,忍受我:

public interface Command<R>
{
    public R execute();//parameter R is the type of object that will be returned as the result of the execution of this command
}

public abstract class BasicCommand<R> implements Command<R>
{
}

public interface CommandProcessor<C extends Command<?>>
{
    public <R> R process(C<R> command);//this is my question... it's illegal to do, but you understand the idea behind it, right?
}

//constrain BasicCommandProcessor to commands that subclass BasicCommand
public class BasicCommandProcessor<C extends BasicCommand<?>> implements CommandProcessor<C>
{
    //here, only subclasses of BasicCommand should be allowed as arguments but these
    //BasicCommand object should be parameterized by R, like so: BasicCommand<R>
    //so the method signature should really be
    //    public <R> R process(BasicCommand<R> command)
    //which would break the inheritance if the interface's method signature was instead:
    //    public <R> R process(Command<R> command);
    //I really hope this fully illustrates my conundrum
    public <R> R process(C<R> command)
    {
        return command.execute();
    }
}

public class CommandContext
{
    public static void main(String... args)
    {
        BasicCommandProcessor<BasicCommand<?>> bcp = new BasicCommandProcessor<BasicCommand<?>>();
        String textResult = bcp.execute(new BasicCommand<String>()
        {
            public String execute()
            {
                return "result";
            }
        });
        Long numericResult = bcp.execute(new BasicCommand<Long>()
        {
            public Long execute()
            {
                return 123L;
            }
        });
    }
}

基本上,我希望通用的“处理”方法决定Command对象的通用参数的类型。目标是能够将CommandProcessor的不同实现限制为某些实现Command接口的类,同时能够调用实现CommandProcessor接口的任何类的处理方法,并使其返回由Object指定的类型的对象。参数化的Command对象。我不确定我的解释是否足够清楚,所以请让我知道是否需要进一步的解释。我想,问题是“这是否有可能做到?”如果答案为“否”,那将是最好的解决方法(我自己想到了一对,但我想提出一些新主意)

最佳答案

不幸的是,您不能这样做。由于您希望按照CommandProcessor定义Command接口,因此必须准备使用任何类型的Command实例-泛型不能将其限制为BasicCommand-如果可以的话,那么BasicCommandProcessor子类将不会实现CommandProcessor接口。

或者,从另一个角度来看,给定CommandProcessor接口,泛型无法确保仅使用BasicCommand实例调用此接口。要做到这一点,就需要知道其蕴含力,并且与多态性和接口的观点背道而驰。

您可以参数化命令的结果,但不能参数化具体的命令类。

public interface Command<R>
{
    public R execute();//parameter R is the type of object that will be returned as the result of the execution of this command
}

public abstract class BasicCommand<R> implements Command<R>
{
}

public interface CommandProcessor
{
    public <R> R process(Command<R> command);
}

public class BasicCommandProcessor implements CommandProcessor
{
    public <R> R processBasicCommand(BasicCommand<R> command)
    {
       return command.execute();
    }

    public <R> R process(Command<R> command)
    {
       return processBasicCommand((BasicCommand<R>)command);
    }
}

最简单的方法是提供一种接受所需特定类型的方法,并在通用方法中进行调用。 (请参阅上面的BasicCommandProcessor。)

07-26 03:20