-4

I am trying to repeat an instant variable call N times in java as follows:

System.out.println(ClassName.InstantVarialble);

System.out.println(ClassName.IntantVariable * N); 
//where N = 3, should preform the following:

System.out.println(ClassName.IntantVariable.IntantVariable.IntantVariable);

Is this even possible? if not, is there a built in java function that can do what im asking for or can i get ideas on how to code a method that could repeat the instant call?

im working on Doubly Linked List that doesnt return to the null position here is an image of what im trying to accomplish doesnt return to null position. its similar to what they do in this video https://youtu.be/BspFdzVvYe8?list=PLPf65fTMT69iUS9A43IyaB1Rz3BBOiPpa

King_Jeff
  • 11
  • 2
  • No it isn't possible – Jens Jul 14 '17 at 19:27
  • how can i code something to do what im asking for? – King_Jeff Jul 14 '17 at 19:30
  • Why do you think you want to do this? – Joe C Jul 14 '17 at 19:37
  • I am working on a doubly linked list that doesnt return to the null position if that makes sense. I need to change the previous pointer and the next pointer, of the linked list to reflect the changes. once an item has been added to the linked list the previous and next pointer should never point back to the null position. – King_Jeff Jul 14 '17 at 19:43

1 Answers1

0

It's possible with reflection, though I don't recommend it. I'm not sure why you would want to do this: the fields would have to be named identically.

class A {
    public static int field = 99;
}
class B {
    public static A field = new A();
}
class C {
    public static B field = new B();
}

public class Blah
{
    public static String foo(Class<?> clazz, String fieldName, int n)
        throws NoSuchFieldException, IllegalAccessException
    {
        for (int i = 0; i < n - 1; ++i)
        {
            clazz = clazz.getField(fieldName).get(null).getClass();
        }

        return clazz.getField(fieldName).get(null).toString();
    }

    public static void main(String... args)
        throws NoSuchFieldException, IllegalAccessException
    {
        System.out.println(foo(C.class, "field", 1));
        System.out.println(foo(C.class, "field", 2));
        System.out.println(foo(C.class, "field", 3));
    }
}

Run it here. Sample output:

B@65e579dc
A@61baa894
99

You will need to allow access if want to be able to do this for private fields.

Michael
  • 41,989
  • 11
  • 82
  • 128