Reputation: 19546
I have some classes that looks like this
class Person {
public String name;
public String age;
public String dateOfBirth;
/* more fields */
public String[] fieldsToReflect()
{
return new String[] { "name", "age"}
}
}
class Vehicle {
public String make;
public String model;
public String mileage;
/* more fields */
public String[] fieldsToReflect()
{
return new String[] { "make", "model" }
}
}
Person
objects have a number of fields, but when getting fields from instances of Person
I only want to allow others to access name
and age
.
Since I may be working with arbitrary objects (eg: a Vehicle
object), I figured the easiest way to uniformly handle all of the objects within the application is to have each object tell me what fields I can get from them.
Are there other approaches I could consider when it comes to controlling what fields should be retrieved from an object?
Upvotes: 0
Views: 66
Reputation: 5018
You may use annotations, like
@ReflectableFields({"name", "age"})
class Person {
public String name;
public String age;
public String dateOfBirth;
}
with @ReflectableFields
defined as
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ReflectableFields {
String[] value();
}
Or field by field :
class Person {
@Reflectable
public String name;
@Reflectable
public String age;
public String dateOfBirth;
}
with @Reflectable
defined as
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Reflectable {
// No field needed
}
The first solution is less verbose, but names in annotation have to be updated along with field names. The second solution seems more verbose, but field name don't need to be explicit.
Upvotes: 1