java 如何在java中创建自定义数据类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4942063/
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-10-30 08:42:55  来源:igfitidea点击:

how to create a custom datatype in java?

java

提问by Sameek Mishra

I want to create an custom datatype in Java,for example datatype Email , that having following method isValidate(String email),isEmailExist(String email),getDomain(String email), get Id(String email),just like Integer class in java.

我想在 Java 中创建一个自定义数据类型,例如数据类型 Email ,具有以下方法 isValidate(String email),isEmailExist(String email),getDomain(String email), getId(String email),就像 java 中的 Integer 类.

Integer is a class and I can initialise the object of Integer class as follows:

Integer 是一个类,我可以按如下方式初始化 Integer 类的对象:

Integer i = 100;

I created my class Email and I want to initialise it as follows

我创建了我的类电子邮件,我想按如下方式初始化它

Email e = "sam";

How can i perform this functionality in my Email class.

我如何在我的电子邮件类中执行此功能。

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Email { private String email; public Email(String email) { this.email=email; }

Email() {  
}

public Boolean isvalid(String email)
{

String lastToken = null; Pattern p = Pattern.compile(".+@.+\.[a-z]+"); // Match the given string with the pattern Matcher m = p.matcher(email); // check whether match is found boolean matchFound = m.matches(); StringTokenizer st = new StringTokenizer(email, "."); while (st.hasMoreTokens()) { lastToken = st.nextToken(); }

if (matchFound && lastToken.length() >= 2 && email.length() - 1 != lastToken.length()) { return true; } else return false; } public String toString() { return email; } }

Thanks

谢谢

回答by Dan Grossman

Create an Email class. Java 101; any book or free tutorial of the Java language will get you started.

创建一个电子邮件类。爪哇 101; 任何有关 Java 语言的书籍或免费教程都可以帮助您入门。

回答by Viktor Mellgren

You cannot instantiate it as you write, the closest would be using a constructor:

您无法在编写时实例化它,最接近的是使用构造函数:

Email e = new Email("Sam");