Is there any way to generate code in Interface on implementing it in a class

674 Views Asked by At

I want to add all the abstracts of getter and setter of a class to the interface that I am implementing in that particular interface. I also want to generate a final variable that resembles class variable. This variable can be used as string to access class variable after deserializing.

Eg:

public class Abc implements IAbc{

private String oneVariable;

 public String getOneVariable(){
    return oneVariable;
 }
}

On implementing the above class with interface IAbc. IAbc should contain the following code:

public interface IAbc{
  public static final String ONE_VARIABLE = "oneVariable";

  public getOneVariable();

}

I have tried googling for the solution but could not get any. Also the methods in class should have the annotation @Override after this code is generated.

1

There are 1 best solutions below

3
On

TL;DR This is an interesting programming challenge, but I find very little use for this in real life scenarios.
Here the name of the first string variable is known before hand, you can directly store the final value in this instead of the round-about way of storing the name of second variable.


If understand correctly you are trying to access a (String) variable of a class whose name will be in another string variable. This is possible using java reflection.

Additionally you want this code to be placed in an interface such that it can be (re)used in all the classes implementing it.

import java.lang.reflect.Field;

interface Foo {

    public default String getStringVar() 
            throws NoSuchFieldException, IllegalAccessException {
        // get varName
        Class thisCls = this.getClass();
        Field varNameField = thisCls.getField("varName");
        String varName = (String) varNameField.get(this);

        // get String variable of name `varName`
        Field strField = thisCls.getField(varName);
        String value = (String) strField.get(this);

        return value;
    }
}


class FooImpl1 implements Foo {
    public final String varName = "str1";
    public String str1 = "some value";
}

class FooImpl2 implements Foo {
    public final String varName = "str2";
    public String str2 = "some other value";
}

class Main {
    public static void main(String[] args) 
            throws NoSuchFieldException, IllegalAccessException {
        System.out.println(new FooImpl1().getStringVar());
        System.out.println(new FooImpl2().getStringVar());
    }
}

Here I have two String members in classes implementing interface Foo. The first varName contains the variable name of the second String, second String variable contains the data.
In the interface using reflection I am first extracting the variable name stored in varName, then using this extracting the value of second String.