如何创建类似于 C++ 模板类的 Java 类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1854335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:18:01  来源:igfitidea点击:

How to create a Java class, similar to a C++ template class?

javac++generics

提问by sivabudh

How do I write an equivalent of this in Java?

我如何在 Java 中编写与此等效的代码?

// C++ Code

template< class T >
class SomeClass
{
private:
  T data;

public:
  SomeClass()
  {
  }
  void set(T data_)
  {
    data = data_;
  }
};

采纳答案by Laurence Gonsalves

class SomeClass<T> {
  private T data;

  public SomeClass() {
  }

  public void set(T data_) {
    data = data_;
  }
}

You probably also want to make the class itself public, but that's pretty much the literal translation into Java.

您可能还希望将类本身公开,但这几乎是 Java 的直译。

There are other differences between C++ templates and Java generics, but none of those are issues for your example.

C++ 模板和 Java 泛型之间还有其他差异,但对于您的示例而言,这些都不是问题。

回答by Moishe Lettvin

You use "generics" to do this in Java:

您可以使用“泛型”在 Java 中执行此操作:

public class SomeClass<T> {
  private T data;

  public SomeClass() {
  }

  public void set(T data) {
    this.data = data;
  }
};

Wikipedia has a good description of generics in Java.

维基百科对 Java 中泛型有很好的描述。

回答by Bill

/**
 * This class is designed to act like C#'s properties.
 */
public class Property<T>
{
  private T value;

  /**
   * By default, stores the value passed in.
   * This action can be overridden.
   * @param _value
   */
  public void set (T _value)
  {
    value = _value;
  }

  /**
   * By default, returns the stored value.
   * This action can be overridden.
   * @return
   */
  public T get()
  {
    return value;
  }
}

回答by Jim Yanyan Bai

public class GenericClass<T> {
    private T data;

    public GenericClass() {}

    public GenericClass(T t) {
        this.data = t;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    // usage 
    public static void main(String[] args) {
        GenericClass<Integer> gci = new GenericClass<Integer>(new Integer(5)); 
        System.out.println(gci.getData());  // print 5; 

        GenericClass<String> gcs = new GenericClass<String>(); 
        gcs.setData("abc");
        System.out.println(gcs.getData());  // print abc;
    }
}