I've got the following example class:
public class MyPermission implements Permission {
public static final String READ = "read";
public static final String UPDATE = "update";
public static final String DELETE = "delete";
@Override
public boolean isGranted(String permission) {
switch(permission) {
case READ: return read;
case UPDATE: return update;
case DELETE: return delete;
default: return false;
}
}
private boolean read;
public boolean isRead() { return read; }
public void setRead(boolean read) { this.read = read; }
private boolean update;
public boolean isUpdate() { return update; }
public void setUpdate(boolean update) { this.update = update; }
private boolean delete;
public boolean isDelete() { return delete; }
public void setDelete(boolean delete) { this.delete = delete; }
}
And I want to simplify things a bit, because there will be created much more of these classes. The schema is always the same:
- some
public final static String
Permissions (must be accessible inside Annotations) - each of those Permissions has a corresponding boolean field
- method
isGranted
returns the value of the corresponding boolean field
As you can see in the example code: I've go to write a lot of code, to achieve this and I can't figure out how to simplify things.
There are 2 things I could imagine:
call
super(READ, UPDATE, DELETE);
inside the constructor and let the super class handle theisGranted(...)
method via reflection.just call
super();
inside the constructor and the class will find thepublic static final String
fields itself and create the fields and getter/setter dynamically, because I don't need them in my code - they just have to be there at runtime.
Or is there any cool new feature in Java 8, so I can do this:
public MyPermission() {
super(new HashMap<String, GetterMethod>() {{
put(READ, this::isRead);
put(UPDATE, this::isUpdate);
put(DELETE, this::isDelete);
}});
}
So I could dynamically invoke the corresponding getter method, like:
public boolean isGranted(String permission) {
return permissionMap.get(permission).execute();
}
(or even using the field, instead of the getter method)
It would be cool, if there's a simple and nice solution for this :)
Thanks in advance!