tags:

views:

81

answers:

6

I'd like to be able to create an object that is created like a String object, and when created verifies that the String value is an appropriate option.

I.E. SpecificString can be "Bob" or "Jim".

SpecificString BadName = "Sam" //Throws exception SpecificString GoodName = "Bob" //Does not throw exception.

The most important functionality is that when it is accessed it must behave like a string when accessed.

printf(SpecificString); // outputs Bob.

Is this possible?

+1  A: 

EDIT: Oops, thought this was a C# question to start with :)

Java doesn't allow user-defined conversions, so this isn't going to work in the way that you've shown. You'll need a static Parse method or a constructor, or something similar.

If there are only certain values which are permitted, could you use an enum instead?

Jon Skeet
+1  A: 

If I understand your point correctly, you want to ensure that a given object is a String limited to a specific set of possible values.

I'd go for Enums, in this case. Just use the standard Enums if you are using a recent Java version, or roll up the "old" DIY version that may perhaps be more appropriate to your specific problem.

For an example of the latter one, see this

p.marino
+2  A: 

You probably want to use an enum for this. Enums were introduced to Java in version 1.5. You can read about them in the official documentation here.

If, for some reason, you are unable to use Java 1.5, the Apache commons-lang library has a reasonably good substitute.

Syntactic
+2  A: 

If the question is can it be created like a String aka. String s = "foo" the answer is no. Only Strings can be constructed that way and String is final so you won't be able to define a child class for it...

If you look for the best way to create Strings from a given Set you may use a StringFactory or look at the other answers...

pgras
+2  A: 

As has been said using the = operator is not possible.

For printf(SpecificString) you should override Object.toString():

@Override
public String toString(){
    //return a String representation of the Object;
}
zockman
Awesome! toString(). Sounds good.
Zachary Spencer
A: 

You can't. But if you could do this it would not be possible to distinguish a normal atribution from one that throws an exception (assuming your exception is unchecked) or do anything on atribution. Using a method call you would be making clear to someone using your class that some validation exists, and in Eclipse I could see what this validation is with a ctrl+click.

Lucass