[英]Is there a way in Java to build custom types based on java.lang base Types (e.g. String)?
is there a way in Java to create a custom class based on a primitive Java base class to give the derived class a semantic? Java中有没有一种方法可以基于原始Java基类创建自定义类,以使派生类具有语义?
Example: I want to create a LinkedHashMap<LastName, Age> ages
where LastName
is a custom type of String
and Age
a custom type derived from Integer
. 示例:我想创建一个
LinkedHashMap<LastName, Age> ages
,其中LastName
是String
的自定义类型, Age
是从Integer
派生的自定义类型。 I just tried to create my own class 我只是尝试创建自己的课程
public class LastName extends String {
//(no code in here, LastName has the same functionality as String)
}
but this is not possible. 但这是不可能的。 Is there another way to achieve what I want?
还有另一种方法可以实现我想要的吗?
What you probably want is type-aliases. 您可能想要的是类型别名。 Java does not support this.
Java不支持此功能。
The best way would be to create a wrapper class, something like this: 最好的方法是创建一个包装器类,如下所示:
class LastName{
private String value;
}
Another way is to name your variables correctly, eg don't do: 另一种方法是正确命名变量,例如不要:
String string = "Smith";
But rather do: 而是这样做:
String lastName = "Smith";
or just document your code with comments and javadoc. 或仅使用注释和javadoc记录您的代码。
Sidenote: If you still want to use type aliases you may want to use the Kotlin programming language which can compile to java-code (and more).
旁注:如果您仍想使用类型别名,则可能要使用Kotlin编程语言 ,该语言 可以编译为Java代码(及更多)。
NO 没有
Those classes are final. 这些课程是最后的。
Usual way to deal with it is to create wrapper class. 通常的处理方法是创建包装器类。
For example: 例如:
public class LastName {
private final String value;
public LastName(String value) {
this.value = value;
}
public String get() { return value; }
}
A String
implements a CharSequence
interface, just like StringBuffer
and StringBuilder
class. String
实现CharSequence
接口,就像StringBuffer
和StringBuilder
类一样。 You can follow the same process. 您可以遵循相同的过程。
public final class LastName implements CharSequence {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.