2

想象以下用 C# 编写的代码:

public class Provider<T>
{
   T GetValue();  // implementation skipped for brevity
}

//

public class Converter<T1, T2>
{
    T2 Convert(T1 value);// implementation skipped for brevity
}

//

public class SomeClass // No Generics Here
{

    public T2 DoSomething<T1, T2>()
    {
        T1 value = new Provider<T1>().GetValue();
        T2 result = new Converter<T1, T2>().Convert(value);

        return result;
    }
}

// and the usage
...
SomeClass some = new SomeClass();
SomeOtherType result = some.DoSomething<SomeType, SomeOtherType>();

是否可以使用 Java 实现相同的功能 - 我想知道如何通过在方法使用中提供类型参数来调用 Java 中的方法,如上所示。我已经在 .NET 中完成了这项工作,并且我知道 Java 支持类型约束和推理,我只是把它的语法弄乱了。

4

2 回答 2

2

Provider 和 Converter 都很好,你的 DoSomething 方法应该像这样重写:

public <T1, T2> T2 doSomething() {
  T1 value = new Provider<T1>().GetValue();
  T2 result = new Converter<T1, T2>().Convert(value);
  return result;
}

可以这样使用:

SomeClass instance = new SomeClass();
Integer something = instance.<String, Integer>doSomething();
于 2012-01-03T16:34:36.307 回答
1

这是一个使用一些泛型的 Java 类,您可以将其作为参考。事实上,Java 的泛型与 C++/C# 模板并不完全相同。但是有一些限制和一些乏味的 Java 编译器警告,您可以使用 Java 的泛型实现类似的模板。

public class Parameter {

    /* Innerclass used for holding a generic value.
     *
     */
    protected class Value<T> {

        protected T val;

        public void set(T val) {

            this.val = val;
        }

        public T get() {

            return val;
        }
    }

    // Parameter name
    String name;
    // Parameter value
    Value value;


    /* Construct with empty name and value pair.
     * Use the set method for getting something meaningful.
     */
    public Parameter() {}

    /* Construct with name and value pair.
     *
     */
    public <V> Parameter(String name, V value) {

        set(name, value);
    }

    /* Set name and value pair.
     *
     */
    public <V> void set(String name, V value) {

       this.name  = name;
       this.value = new Value();
       this.value.set(value);
    }

    /* Get the parameter name.
     *
     */
    public String getName() {

        return name;
    }

    /* Get the parameter value.
     *
     */
    public <V> V getValue() {

        //! NOTE the caller must be sure that the proper value type is carried out.
        return ((Value<V>) value).get();
    }

    /* Set the parameter value.
     *
     */
    public <V> void setValue(V value) throws Exception {

        //! NOTE the caller must be sure that the proper value type is used.
        if (value.getClass() != this.value.get().getClass() ) {

            throw new Exception( "trying to set an incompatible parameter value" );
        }

        this.value.set(value);
    }

    /* Return the value class.
     * 
     */
    public Class getValueType() {

        return value.get().getClass();
    }
}
于 2012-01-03T16:47:17.490 回答