mercredi 11 décembre 2019

Design pattern compatible with reflection

I have some code that relies on reflection (working with a third-party libarary) to get the fields of a class. Many of these classes use a mix of the same fields, some nearly identical but with a few differences.

This has led to a ton of code duplication, but I'm not sure of a nice pattern around it due to the reliance reflection.

According to the documentation:

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

This rules out an Abstract class or any inheritence-related solutions.

Here's a code example (MyField represents a third-party library object):

ClassA.java

public class ClassA {
    private final Field[] myFields;

    private final MyField a = new MyField(1);
    private final MyField b = new MyField(2);
    private final MyField c = new MyField(3);

    public ClassA() {
        myFields = this.getClass().getDeclaredFields();
    }

    public void doStuff(Field[] myFields) {
        // do something...
    }

    public Field[] getFields() {
        return Arrays.copyOf(myFields, myFields.length);
    {
}

ClassB.java

public class ClassB {
    private final Field[] myFields;

    private final MyField a = new MyField(1);
    private final MyField c = new MyField(3);
    private final MyField d = new MyField(4);

    public ClassB() {
        myFields = this.getClass().getDeclaredFields();
    }

    public void doStuff(Field[] myFields) {
        // do something...
    }

    public Field[] getFields() {
        return Arrays.copyOf(myFields, myFields.length);
    {
}

Note that ClassA and ClassB share fields a and c and methods getFields() and doStuff().

Is there any way to shore up some of this duplication without affecting the reflection?





Aucun commentaire:

Enregistrer un commentaire