0

I'm learning OOP and java with an online-course. This chapter is about access modifiers and you have to call every possible attribute of TestRobot.

Now I've tried it with an array of the attributes and wanted to use a for-loop to check them all if they exist. Of course, I could just do it 4 times but this is redundant somehow. :D Now I have an error that there is no symbol attributes. My suggestion is that the compiler is checking in the class robots for "attributes".

Is there a possibility to tell java that attributes is an array or variable of the class Terminal instead part of the class robot itself? For example in JavaScript you would just write robots[attributes[i]].

Is it even possible to call EVERY attribute of a class?

class TestRobot {
    private int secretKey = 602413;
    protected int numberOfProcessorCores = 4;
    boolean hasFirewall = false;
    public String id = "58-08-2";
}


class Terminal {
    String[] attributes = {"secretKey", "numberOfProcessorCores", "hasFirewall", "id"};
    
    public void hackRobot(TestRobot robot) {
        for(int i = 0; i < attributes.length; i++){
            if(robot.attributes[i]) {
                System.out.println(attributes[i]);
            }
        }
    }
}
3
  • 1
    Technically you can do this using java Reflection to get the fields of a class but that's quite an advanced technique if you're only just learning about access modifiers. Commented Apr 27, 2021 at 12:55
  • The JavaScript example you give seems to be for iterating HTML Attributes, not JavaScript / object attributes Commented Apr 27, 2021 at 12:57
  • @DLynch Thank you. I just completed the task with the "old" fashioned way. :D Maybe I will use java Reflection API later. Was just wodnering, because in other languages it seems to be so easy. Commented Apr 29, 2021 at 9:30

1 Answer 1

1

Yes, this is possible through reflection API. You can get a list of attributes dynamically with TestRobot.class.getDeclaredAttributes(), then you can programmatically inspect the type of each field, its visibility, and you can get/set the values of those attributes on an instance of TestRobot.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.