0

Get all attributes easy way

is it possible to get the values of all attributes of an object without creating a getter method one by one for each attribute? i mean a car object in Vehicle class has name, speed, color, and i would like to get all information at once about this car. Sorry for bad english.

29th Apr 2017, 12:02 PM
Benedek Máté Tóth
Benedek Máté Tóth - avatar
4 Réponses
+ 1
You can create getter for all data of similar type you need and return it in array. Alternatively you can use Object[] array as result of getter and return all data independent of type but it is a bad practice, i do not recommend to code like that.
29th Apr 2017, 12:26 PM
Jeth
Jeth - avatar
+ 1
public class Soldier { String name; String rank; Soldier() { name = "Hartman"; rank = "Gunnery Sergeant"; } String[] getRankAndName() { String[] result = new String[2]; result[0] = rank; result[1] = name; return result; } public static void main(String[] args) { Soldier s = new Soldier(); String[] text = s.getRankAndName(); //we get name and rank (two attributes) with one method System.out.println(text[0] + " " + text[1]); //outputs "Gunnery Sergeant Hartman" } }
2nd May 2017, 8:15 PM
Jeth
Jeth - avatar
+ 1
i got it, thank you very match!!!!
2nd May 2017, 9:46 PM
Benedek Máté Tóth
Benedek Máté Tóth - avatar
0
how we get it as sn array? sorry i am new in java.
2nd May 2017, 4:24 PM
Benedek Máté Tóth
Benedek Máté Tóth - avatar