Joon. P
Joon. P

Reputation: 2298

JAVA - how to use Enum as public static final String in different classes?

I want to store constants in one class, and have access to it from different classes.

This is how I created a class for constants, "Keys"

public class Keys {
    public static class SQLite {  
        public static final int DB_VERSION = 8;
        public static final String DB_NAME = "my_db.sqlite";
        public static final String TABLE_NAME = "table_name";

        public enum Column {
            NAME("name"),
            PHONE("phone"),
            ADDRESS("address");

            private String value;

            Column(String value) {
                this.value = value;
            }

            public String toString() {
                return value;
            }
        }
    }


    public static class Constants {  
        public static final String CONST1 = "const1";
        public static final String CONST2 = "const2";

        public enum Random {
            ONE("one"),
            TWO("two"),
            THREE("three");

            private String value;

            Random(String value) {
                this.value = value;
            }

            public String toString() {
                return value;
            }
        }
    }
}

Now, inside a class called "MyActivity",

I know I can use enums like this:

String name = Keys.SQLite.Column.NAME.toString();

But is there a way to shorten the prefix?

so that I can access it in a simpler way:

Column.Name.toString();

instead of:

Keys.SQLite.Column.Name.toString();

Upvotes: 2

Views: 779

Answers (3)

Roland
Roland

Reputation: 23252

As Azodious already stated, you can import it via

import Keys.SQLite.Column;

If that does not suffice your needs, you may also use a static import, like:

import static Keys.SQLite.Column.NAME;

This way you can now use

String name = NAME.toString();

Upvotes: 2

Anurag
Anurag

Reputation: 51

Directly import the enum in your class:

import Keys.SQLite.Column;

and then type Enum name and enum which you want to get :

Column.NAME;

Upvotes: 1

Azodious
Azodious

Reputation: 13872

You can import the enum in MyActivity class:

import Keys.SQLite.Column;

and just use

String name = Column.NAME.toString();

Upvotes: 2

Related Questions