[英]How can I make a new data type called Identifier that every instance of it should be a valid identifier name?
can I make this new class as I asked in the title, this is my attempt. 我可以按照标题中的要求进行这门新课吗,这是我的尝试。
import javax.lang.model.*;
public class Ide{
public Ide New(String ide){
if (SourceVersion.isName(ide)) {
return ide;
}
}
}
But it won't compile because I can't convert the String ide to type Ide, how can I do it? 但是它无法编译,因为我无法将String ide转换为Ide类型,我该怎么做? I need to have type Ide, thanks in advance. 我需要输入Ide类型,谢谢。
This code has several issues: 此代码有几个问题:
String
is final
. String
是final
。 This means, no class can inherit from String
. 这意味着任何类都不能从String
继承。 New
should be static
, otherwise the method won't make any sense. New
应该是static
,否则该方法将毫无意义。 Requiring an instance of a class to create other instances is like the chicken-and-egg-problem, only you haven't got either one. 要求一个类的实例创建其他实例就像“鸡与蛋”问题一样,只是您一个都没有。 New
is really bad style. 调用方法New
确实是不好的样式。 new
is a keyword in java and you're provoking coding errors, make your code less readable... . new
是Java中的关键字,并且会引起编码错误,使代码的可读性降低...。 And method names shouldn't be uppercase. 而且方法名称不应大写。 String
, a String
-parameter wouldn't automatically be an Ide
-instance. 即使可以从String
扩展类,但String
-parameter不会自动成为Ide
-instance。 Thus the return ide;
因此, return ide;
won't compile. 不会编译。 A solution to your problem would be: 解决您的问题的方法是:
Use a private
constructor combined with a static
factory-method. 使用private
构造函数和static
工厂方法。 The class can only be a wrapper-class though. 该类只能是包装器类。 Simply implement it in adapter-style to provide the methods provided by String
that are required: 只需以适配器样式实现即可提供String
提供的所需方法:
class Ide{
private String str;
private Ide(String str){
this.str = str;
}
public static Ide createIde(String str)
throws IllegalArgumentException
{
if(validIdentifier(str))
return new Ide(str);
else
throw new IllegalArgumentException("Invalid identifier: " + str);
}
//examples for adapter-like method-implementation
public String toString(){
return str.toString();
}
public char charAt(int i){
return str.charAt(i);
}
}
Your code is wrong on many many levels. 您的代码在许多层次上都是错误的。 I suggest that you first learn about the fundamentals of Java; 我建议您首先了解Java的基础知识。 before you consider writing your own code. 在考虑编写自己的代码之前。
Problems in your code: 您的代码中的问题:
Long story short: you are trying to build a skyscraper, but you are already lacking the skills to dig a whole in the ground. 长话短说:您正在尝试建造摩天大楼,但您已经缺乏在地面上挖掘整块土地的技能。 This is not meant to insult you, but the fact is: you have to do a lot of learning first. 这并不是要侮辱您,而是事实:您必须首先学习很多东西。 Don't expect us to explain everything to you that you would need to come up with a reasonable program. 不要指望我们向您解释所有您想出一个合理的程序所需的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.