How would I create an object that uses String type behaviour for creation?
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 po开发者_StackOverflowssible?
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;
}
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.
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...
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?
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
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.
精彩评论