开发者

What's the best way to pass a String as a separate type?

I want to create a method like example below to make sure that a user is only able to provide a value that corresponds to one of the constants defined in the Name class:

public class Name{
 public static String JOHN = "John";
 public static String MARY = "Mary";
 public static String TAB = "\t";
}

public void example(Name name){
 test(na开发者_开发问答me);
}

public void test(String name){
 System.out.println(name);
}

Basically the example method just takes a String argument. But I want to restrict the types of Strings that could be passed by the user so if I make the parameter String name it will be open to any type of input.

Is there a simpler way to do this?


Use an enum?

public enum Name{
 John, Mary;
}

public void test(Name name){
 System.out.println(name);
}

Its a bad idea to mix concepts, TAB is clearly not a person's name. However, if the example were different you can do this.

public enum Name{
 John, Mary, 
 TAB { public String toString() { return "\n"; } };
}


Create an enum:

public enum Name {
  John, Mary
}
public void example(Name name){
  test(name);
}

You can also add methods, state, and constructors to your enum as well:

public enum Name {
  John(23), Mary(20)

  private int age;

  private Name(int age) {
    this.age = age;
  }

  public int getAge() {
    return age;
  }
}

I find I do that kind of thing a lot.

Since I see you've now added the TAB one, how about this:

public enum Name {
  JOHN("John"), Mary("Mary"), TAB("\n")

  private int str;

  private Name(int str) {
    this.str = str;
  }

  public String toString() {
    return str;
  }
}


Strings cannot be subclassed, hence you cannot immediately do what you want to.

Either consider using ENUM's, or explicitly test the passed string for valid values in the constructor, and throw a RuntimeException if it is unacceptable.


I think your code has an error because you are passing the object called name that is of type Name into example but into test you are getting a String and it is getting passed name from example so I'm not sure what you are trying to do. Can you please elaborate?


why don't you use ENUM?

public enum Name{
    John, Marry
}

and then you can write method like

public void example (Name name){
    test(name);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜