D
D
Di Ma2018-02-08 13:24:21
Java
Di Ma, 2018-02-08 13:24:21

How to iterate over an object in a loop?

Hello!
Java is my first strict language and I'm frankly puzzled..

// main
User u1 = new User("Jack", 41);
u1.info();


class User {

  public String name;
  public int age;

  public User(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public void info() {
    // как обойти в цикле все свойства текущего объекта?
  }
}

And is it possible to create simple objects like in JavaScript without calling a constructor?
var obj = { name: "Jack", age: 33 };

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2018-02-08
@sergey-gornostaev

It is impossible to bypass fields without reflection, and it is impossible to create an object without a constructor.

Y
Yerlan Ibraev, 2018-02-08
@mad_nazgul

Here you are not here.
Static typing however.
You can bypass the properties of an object in a loop through reflection
. But it’s better not to do this. Because it is not necessary for your task. Because static typing!

Y
Yuri, 2018-02-08
@YuryBorodkin

As the comrades above said, Java does not work that way.
A lot of boilerplate, yes. But as I understand it, you need a description of the object - and it can be generated by an IDE or a code generator like project Lombok

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question