How to create a Java class, similar to a C++ template class?
如何在Java中编写一个等价的代码?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // C++ Code template< class T > class SomeClass { private: T data; public: SomeClass() { } void set(T data_) { data = data_; } }; |
1 2 3 4 5 6 7 8 9 10 | class SomeClass<T> { private T data; public SomeClass() { } public void set(T data_) { data = data_; } } |
您可能还希望使类本身公开,但这几乎是文字翻译成Java。
C++模板和Java泛型还有其他区别,但这些都不是你的例子中的问题。
在Java中使用"泛型"来实现这一点:
1 2 3 4 5 6 7 8 9 10 | public class SomeClass<T> { private T data; public SomeClass() { } public void set(T data) { this.data = data; } }; |
维基百科对Java中的泛型有很好的描述。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /** * 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; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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; } } |