java - Using class annotations or static properties -
i’m new java , wondering best practices here.
say have generic class (e.g. car
), , inherited classes (honda
, subaru
) share properties.
public abstract class car { public static short id; } public class honda extends car { public static final short id = 1; } public class subaru extends car { public static final short id = 2; }
doesn’t break dry principle? using annotation then?
@retention(retentionpolicy.runtime) @target(elementtype.type) public @interface id { public short value(); } public abstract class car { } @id(1) public class honda extends car { } @id(2) public class subaru extends car { }
it of course bit question of taste. not recommend you. annotations metainformation mark fields, methods , classes. id (or nbseats) rather field annotation.
i prefer in case:
public abstract class car { protected static short id; public static short getid() { return id; } } class honda extends car { static { id = 1; } } class subaru extends car { static { id = 2; } }
edit: sorry: solution flawed :-( car, honda , subaru share same field. have on that:
public static void main(string[] args) { new honda(); new subaru(); system.out.println(honda.getid()); system.out.println(subaru.getid()); }
results in
2 2
i think solution might better:
public abstract class car { protected abstract short id(); public static short getidof(class<? extends car> carclass) throws instantiationexception, illegalaccessexception { return carclass.newinstance().id(); } public static void main(string[] args) throws instantiationexception, illegalaccessexception { system.out.println(car.getidof(honda.class)); system.out.println(car.getidof(subaru.class)); } } class honda extends car { protected short id() { return 1; } } class subaru extends car { protected short id() { return 2; } }
it has advantages:
- it enforces every concrete subclass of car have id (by implementing id()).
- it hides sublasses of car super-class car
- the compiler can check subclasses of car passed getidof()
- it enforces classloader load classes (static-initializers executed when class loaded!)
- many others
it has disadvantages:
- it needs java reflection
- the id()-method non-static
- instances needed invoke id()
- it demands default public constructor in subclasses
- you can pass abstract subclasses getidof()
- many others
keep in mind types of parameters of annotations limited primitive types, string, class, annotation, enumeration , 1-dimensional arrays!
Comments
Post a Comment