views:

104

answers:

6

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.

+5  A: 

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)

Bozho
A: 

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.

matt b
+1  A: 

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

keuleJ
+3  A: 

With Interface you can say

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

and you can make classes to implement that interface and it will will have that field and it will have the same value declared in the interface. Note this is called Constant interface anti-pattern http://en.wikipedia.org/wiki/Constant_interface

If you want classes to give a different value then

interface X {
   public String getType();
}

and implementing classes can implement them and return different values.

(Same with abstract classes)

Calm Storm
+1: I was about to downvote another answer because I didn't realize the OP wanted to have only the identifier, not the value, be the same.
Lord Torgamus
A: 

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.

Juha Syrjälä
A: 

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.

Chris Lercher
But you can't call getType() statically.
Steve Kuo
No, you can't. But that was the second part of his question: "...to have public static final field... Or at least just a public field?" So I understand the question as: I'd like to do it statically, but if that's not possible, then at least non-statically.
Chris Lercher