serg
serg

Reputation: 111265

Any way to force classes to have public static final field in Java?

Is there a way to force classes in Java to have public static final field (through interface or abstract class)? Or at least just a public field?

I need to make sure somehow that a group of classes have

public static final String TYPE = "...";

in them.

Upvotes: 8

Views: 4590

Answers (6)

Kannan Ekanath
Kannan Ekanath

Reputation: 17601

You can define an interface like this:

interface X {
   public static final String TYPE = "...";
}

and you can make classes implement that interface which will then have that field with the same value declared in the interface. Note that this practice is called the Constant interface anti-pattern.

If you want classes to have different values then you can define a function in the interface like this:

interface X {
   public String getType();
}

and implementing classes will have to implement the function which can return different values as needed.

Note: This works similarly with abstract classes as well.

Upvotes: 6

Juha Syrjälä
Juha Syrjälä

Reputation: 34271

Implement an interface in your classes and call a method from that interface, like others have suggested.

If you must absolutely have a static field, you could make an unit-test that will go through the classes and checks with Reflection API that every class has that public static final field. Fail the build if that is not the case.

Upvotes: 0

Chris Lercher
Chris Lercher

Reputation: 37778

Or at least just a public field?

That's IMO the usual way to go: In the superclass, require a value in the constructor:

public abstract class MyAbstract {

  private final String type;

  protected MyAbstract(String type) {
    this.type = type;
  }

  public String getType() {
    return type;
  }
}

This way, all implementations must call that super-constructor - and they don't have to implement getType() each.

Upvotes: 0

Bozho
Bozho

Reputation: 597026

No, you can't.

You can only force them to have a non-static getter method, which would return the appropriate value for each subclass:

public abstract String getType();

If you need to map each subclass of something to a value, without the need to instantiate it, you can create a public static Map<Class<?>, String> types; somewhere, populate it statically with all the classes and their types, and obtain the type by calling TypesHolder.types.get(SomeClass.class)

Upvotes: 8

keuleJ
keuleJ

Reputation: 3486

I don't think it's possible. But you could make an interface with a getType method

Upvotes: 1

matt b
matt b

Reputation: 139921

There is no way to have the compiler enforce this but I would look into creating a custom FindBugs or CheckStyle rule which could check for this.

Upvotes: 1

Related Questions