java - Access level aware dependency injection into inherited field -
at work there process framework. uses keys , containers set parameters without use of dedicated constructors (it's type safe heterogeneous container pattern).
i added dependency injection. below find representative example (it lacks null checks, access control, etc.)
private static void inject(process instance, container c) throws exception { class<?> reference = instance.getclass(); (field field : reference.getdeclaredfields()) { inject inject = field.getannotation(inject.class); key<object> key = new key<>(inject.key()); field.set(instance, c.getobject(key)); } } the implementation working, need enhance in order inject inherited fields.
i had no problem retrieving type hierachy , annotated, inherited fields. in order comply java, must not inject every retrieved field.
only when field is:
publicprotectedpackage-privated, declared in class has same packagereferenceprivate, declared in class enclosesreference, has inner class (non-static nested class).
items 1 - 3 easy check for. have difficulties last item. there elegant solution?
i thougt using java.lang.class.ismemberclass() , comparing class names.
currently check looks this
private static boolean accessallowed(class<?> reference, field field) { int modifiers = field.getmodifiers(); boolean hasaccess = modifier.ispublic(modifiers); hasaccess |= modifier.isprotected(modifiers); // todo fix hasaccess |= modifier.isprivate(modifiers) /* add check defined in 4. */; // no access , not private means field package-private if (!hasaccess && !modifier.isprivate(modifiers)) hasaccess = reference.getpackage().equals(field.getdeclaringclass().getpackage()); return hasaccess; } is there easy and/or efficient way find out whether class enclosed class? or there way find out whether allowed inject?
the following solution should handle private case.
the derived class reference, tries set members inherited fielddeclaringclass
static boolean hasprivateaccessrelation(class<?> reference, class<?> fielddeclaringclass) { boolean ismemberclass = reference.ismemberclass(); boolean isenclosingclass = reference.getname().contains(fielddeclaringclass.getname()); // static nested classes can't access private members of enclosing class return ismemberclass && isenclosingclass && !modifier.isstatic(reference.getmodifiers()); } the code works if derived class inner class of fielddeclaringclass. fails if static nested classes, since these have no access private fields of enclosing classes.
a previous check necessary make sure reference , fielddeclaringclass not equal. because in case static valid modifier, since nested class has access own fields.
Comments
Post a Comment