Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending String for Typesafety - Java

I am considering a design in Java where I want a string object but with more 'type-safety' than just being of class String. This because I have a number of 'POJO' objects for Hibernate, representing my database tables. Each of these classes has a large number of public static fields representing the properties of the class, I.e.:

public class PersistantBean {
    public static String PROP_FIELD_COLUMN_ONE="columnOne";
    public static String PROP_FIELD_COLUMN_TWO="columnTwo";
    // [...]

These properties are used when we need to access a property in a generic way, e.g. for code I am currently writing .parseAndSet(PROP_FIELD_PRICE,"£3.00").

I would like to be able to add a stronger type to the PROP_FIELD_... fields so that I could write

public class PersistantBean {
    public static PropertyName PROP_FIELD_COLUMN_ONE="columnOne";
    public static PropertyName PROP_FIELD_COLUMN_TWO="columnTwo";
    // [...]

with minimal changes to other parts of the project,

so that parseAndSet would look like:

public void parseAndSet(PropertyName prop, String priceToParse)

Essentially, I would like PropertyName to be a type that is like String in everyway apart from the compiler would error if I tried to put a String where a PropertyName was expected, is any design pattern like this possible. (I am shying away from Enums, although now I mention it, Enums may be the way to go.)

like image 265
Ben Page Avatar asked Aug 16 '26 00:08

Ben Page


2 Answers

For Java 1.5 and above, just use an enum type.

For Java 1.4 and below, use the typesafe enum pattern. E.g.

public class Suit {
    private final String name;

    public static final Suit CLUBS =new Suit("clubs");
    public static final Suit DIAMONDS =new Suit("diamonds");
    public static final Suit HEARTS =new Suit("hearts");
    public static final Suit SPADES =new Suit("spades");    

    private Suit(String name){
        this.name =name;
    }
    public String toString(){
        return name;
    }

}
like image 194
donturner Avatar answered Aug 18 '26 17:08

donturner


enum(enumeration) is a better idea, which above mentioned scenario.

eg:

enum PROP_FIELD_COLUMN { columnOne, columnTwo,etc }

like image 23
sethupathi.t Avatar answered Aug 18 '26 18:08

sethupathi.t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!