0

I'm wondering How can I pass field name of a class as parameter to include it in a String?

For example, let's say I have a class A with this members :

public class A {

String name;
String reference;
....

}

What I want, is to be able to initialize a string having as parameters one of the two classe field name to display it dynamically. So for instance, I want to do this :

System.out.println("the field {nameField} belong to class A.");

And in output I would have this :

output : the field name belong to class A.

Is that possible in Java ?

Any help would be much appreciated ?

Regards

YT

  • 2
    Does this answer your question? [How to format strings in Java](https://stackoverflow.com/questions/6431933/how-to-format-strings-in-java) – Ivo Jun 29 '22 at 13:35
  • ClassA ft = new ClassA(); Class ftClass = ft.getClass(); Field[] fields = ftClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { System.out.println("the field"+fields[i] +" belong to class A.") }http://www.avajava.com/tutorials/lessons/how-do-i-list-the-declared-fields-of-a-class.html#:~:text=In%20JavaSW%2C%20it's,%2C%20protected%2C%20and%20private%20fields. – RamanaMuttana Jun 29 '22 at 13:39