1

I'd like a simple way of generating a type safe type based on String.

I have a bunch of places where I usually use just a String to hold opaque UID (example) and I'd like to move away from this.

java.lang.String is final. Ideally I would have liked to extend String but I understand I can't be doing that. What are my best options?

I know I can use an encapsulation but I am looking for something a bit more efficient, if at all possible.

Update: I want a meaningful name for the type i.e. not just UUID everywhere.

8
  • 2
    Why not just have it as a private member? Commented Sep 23, 2012 at 19:12
  • Why not just use a class like java.util.UUID? Commented Sep 23, 2012 at 19:15
  • @Roddy: because I want to have a meaningful name for the type. Commented Sep 23, 2012 at 19:15
  • if i may ask, what would you name the type? mySuperSpecialUUID? i don't see the significance in wrapping a type just to give it a new name. Commented Sep 23, 2012 at 19:23
  • I just want to be as close as a String as possible without the overhead of another type... just to carry a String. Commented Sep 23, 2012 at 19:27

2 Answers 2

3

Because String is declared final, I think encapsulation is the only thing you can do. To provide some level of plug-compatibility, you can declare your class to implement CharSequence.

public class TypeSafeStringBase implements CharSequence {
    protected final String mString;
    protected TypeSafeStringBase(String string) {
        mString = string;
    }
    @Override
    public char charAt(int index) {
        return mString.charAt(index);
    }
    @Override
    public int length() {
        return mString.length();
    }
    @Override
    public CharSequence subSequence(int start, int end) {
        return mString.subSequence(start, end);
    }
    @Override
    public String toString() {
        return mString;
    }
}

public class ParamName extends TypeSafeStringBase {
    ParamName(String string) {
        super(string);
    }
}

public class Prompt extends TypeSafeStringBase {
    Prompt(String string) {
        super(string);
    }
}

// etc.

You might consider also declaring the base class to implement Serializable and Comparable<String> (or a type-safe Comparable for each subclass).

Sign up to request clarification or add additional context in comments.

Comments

3

String inherits from CharSequence

If change your reference type CharSequence, you can use StringBuilder or any other mutable CharSequence.

Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.