I have the following code.
private void relacion() throws Exception {
AlumnoDAO alumnodao = new AlumnoDAO();
for (int i = 0; i < alumnodao.listar().size(); i++) {
System.out.println(alumnodao.listar().get(i));
}
}
Which returns me an ArrayList of objects.
But I need access to such name.
You see me back, id, last name etc ..
But I specifically want the name. I am not sure how.
I'm working with POJO
Example:
System.out.println(alumnodao.listar().get(i).id); // access the 'id' field
System.out.println(alumnodao.listar().get(i).nombre); // access the 'nombre' field
System.out.println(alumnodao.listar().get(i).apelidos); // access the 'apelidos' field
You may need to use a getter to access your arraylist's object member variables depending on their visibility.
The get method of ArrayList returns an object, whose public fields can get accessed. For this reason, you can access the name of the returned object by doing the following:
System.out.println(alumnodao.listar().get(i).nombre);
However, in most cases you don't want to have your fields declared as public. What is usually done instead is to have the fields declared as private and access them with getters and setters.
Related
My question is: why must we pass global variables(members, names) to an object if we want to use it. Isn't a global variable declared for all objects to have access to it?
public class Family {
int members;
String names;
public Family(int members, string names) {
this.members = members;
this.names = names;
}
}
How else do you initialize the variables in an object?
Let me try to explain you this way, Suppose what you were asking was possible then, if we were to create 100 different family objects and if the variables were supposed to have different data, how will that be possible? Because changing a global field would affect all the objects right.
So basically when you create the object you either initialize the fields using a constructor as you have done in the sample or you can use a no args constructor and set the values after the object is created using "Setters".
For more understanding on initialization.
Refer: https://www.google.com/amp/s/www.javaworld.com/article/3040564/java-101-class-and-object-initialization-in-java.amp.html
Hope this helps.
The piece of code mentioned above is actually a class definition . Class is just a template which has member variables and member functions associated with it.Now Object is an instance of the class which has got some values for the variables which is generally get and set using getters and setters respectively.Other operations can be performed by member functions.Constructors are used to initialize the object.
public Family(int members, string names) {
this.members = members;
this.names = names;
}
is a paramaterized constructor used to initialize the object with the parameters passed .This will obviously be useful while creating more than 1 objects of a class as each object will have different values associated with it.To be more clear:
public class Family {
int members;//member variable scope-class level
String names;//member variable scope-class level
public Family(int members, String names) {//int members,string names are parameters scope-constructor ,we can give any name to these two variables like int param_member,String param_names
this.members = members;//LHS specifies the variable- member of the class and RHS specifies variable passed as parameter
this.names = names; //LHS specifies the variable-names of the class and RHS specifies variable passed as parameter
}
}
My question similar to others but it's little bit more tricky for me
I have a Class DummyData having static defined variables
public static String Survey_1="";
public static String Survey_2="";
public static String Survey_3="";
So, i call them DummyData.Survey_1 and it returns whole string value. Similarly do with DummyData.Survey_2 and DummyData.Survey_3
But the problem is when i call them Dynamically its not return their value.
I have a variable data which value is change dynamically like (data=Survey_1 or data=Survey_2 or data=Survey_3)
I use #Reflection to get its value but failed to get its value
I use methods which I'm mentioning Below help me to sort out this problem.
Field field = DummyData.class.getDeclaredField(data);
String JsonData = field.toString();
and
DummyData.class.getDeclaredField("Survey_1").toString()
but this return package name, class name and string name but not return string value.
What I'm doing can some help me??
Getting the value of a declared field is not as simple as that.
You must first locate the field. Then, you have to get the field from an instance of a class.
Field f = Dummy.class.getDeclaredField(“field”);
Object o = f.get(instanceOfDummy);
String s = (String) o;
Doing the simple toString() of the Field will actually invoke the toString() method of the Field object but won't access the value
You must do something like this:
Field field = SomeClass.class.getDeclaredField("someFieldName");
String someString = (String) field.get(null); // Since the field is static you don't need any instance
Also, beware that using reflection is an expensive and dangerous operation. You should consider redesigning your system
I need to create 10 objects from my Variable Class but I'm getting errors.
Here is my code:
for(n=1;n<10;n++){
variableTab[n]= "variable" +""+n;
Variable variableTab[n] = new Variable();
//System.out.println(variableTab[n]);
}
And the errors I have:
Type mismatch: cannot convert from Variable to Variable[]
Syntax error on token "n", delete this token
Duplicate local variable variableTab
I don't know where is the problem because variableTab[] is a String Tab.
You are trying to assign data to an object that hasn't been created yet. Also, you shouldn't start at index 1. Arrays begin at index 0, so essentially, you are robbing yourself of extra space and making things harder on yourself by doing that. This also means that you are creating 9 objects, not 10. Use the implementation below.
Variable [] variableTab = new Variable [10];
for(n=0;n<10;n++){
variableTab[n]= "variable" +""+n;
//System.out.println(variableTab[n]);
}
Update per comments:
If you are trying to store the name of a object, you need to create a member variable to store that name in.
public class Variable {
private String name; //This will be used to store the unique name of the object
//Default constructor for our class
Variable () {
name = "";
}
//Constructor to initialize object with specific name
Variable (String name) {
this.name = name;
}
//We need a way to control when and how the name of an object is changed
public setName (String name) {
this.name = name;
}
//Since our "name" is only modifiable from inside the class,
//we need a way to access it from the program
public String getName () {
return name;
}
}
This would be the proper way to setup a class. You can then control the data for each class in a more predictable way, since it is only able to be changed by calling the setName method, and we control how the data is retrieved from other sections of the program by creating the getName method.
You might want to initialize your object first. If it is an array of objects that you're trying to create, do it this way:
Variable[] variableTab = new Variable[n];
You're trying to assign values to something that hasn't been created yet!
You're code should look like:
for(n=0;n<10;n++){
Variable variableTab[n] = new Variable();
variableTab[n]= "variable" +""+n;
//System.out.println(variableTab[n]);
}
Basically, you're trying to assign a value to something that doesn't exist yet.
I have a requirement to check if the member variables of a class are there in a list or not. For this, I need to get all the variables of a class dynamically (if possible as a list). Is there a method for that in java?
Thanks,
KD
This is the concept of Reflection. You should be able to do something like the following (untested) code snippet:
/**
* #return {#code true} if all of the values of the fields in {#code obj} are
* contained in the set of {#code values}; {#code false} otherwise.
*/
public boolean containsAllValues(HashSet<Object> values, MyClass obj) {
Field[] fields = MyClass.class.getFields();
for (Field field : fields) {
Object fieldValue = field.get(obj);
if (values.contains(fieldValue)) {
return false;
}
}
return true;
}
You may get all of the field names (and their values) by calling Class#getFields()
Example: Consider the class below
public class Test{
public int x, y, z;
}
Test.class.getFields() will return the fields x,y,z, in which you could get their name through Field#getName() and get their value by calling the appropriate get method. In the Test class above, you could do something like this:
Test instance = new Test();
instance.x = 50;
int xValue = Test.class.getField("x").getInt(instance);
The value of xValue would be 50.
For a better demonstration of how it works, please see this.
You're talking about reflection.
Have a look at Class.getFields():
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
See also:
http://forgetfulprogrammer.wordpress.com/2011/06/13/java-reflection-class-getfields-and-class-getdeclaredfields/
There are quite a lot of fishhooks with reflection. Property-based access -- bean properties, of the form getX()/setX() or isX()/setX() -- may be a little better in helping you avoid unstable implementation internal of the class.
You can use the getFields() method, that will return a Field array: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getFields()
And then the getName() method for each element in the Field[] to get the name: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html#getName().
Most answers recommend Class.getFields() but as the JavaDoc states, it will only return the public fields:
Returns an array containing Field objects reflecting all the
accessible public fields of the class or interface represented by this
Class object.
I rarely make my class fields public and rather make them private with getters and setters. To get the list of all fields (including private, protected and package private) you need to use Class.getDeclaredFields():
Returns an array of Field objects reflecting all the fields declared
by the class or interface represented by this Class object. This
includes public, protected, default (package) access, and private
fields, but excludes inherited fields.
Note that unlike Class.getFields(), Class.getDeclaredFields() will not returned the inherited fields. To get those you need to loop through the class hierarchy (loop over Class.getSuperclass() until you reach Object.class). Private fields names could be repeated in parent classes.
Ok my problem isnt really a serious one, im just trying to find a clever way of access/modification of class member variables. Here is the code:
public class Storage{
private int cookies= 0;
private int rolls= 0;
private int candies= 0;
private int lolipops= 0;
private int iceCreams= 0;
public void addCookies(int howMuch){ //this is the dirty way of creating method for
this.cookies = cookies+howMuch; //every member variable
}
public void addValue(String stat, int howMuch){ //i would like to do it only
//by passing the name
//of variable and then cast it as integer
//so that it would relate to my class members
int value = this.(Integer.parseInt(stat)); // <- YES i know its ridiculous
//im just trying to explain what is my aim
value = value + howMuch;
this.(Integer.parseInt(stat)) = value;
}
}
Generally i would like to access a field by passing its name to a method, read value of that member, add to it some value, and then store it. Yes i know that it easily can be done with separate methods, or even with one by using some arraylist and comparisons of member names with parameter passed to method. But i would like to do it "fast" without redundant code writing.
Now i have like 5 members, but what about 15000? My aim is to simplify the whole processing and code writing. So generally is it possible to do such redundant code writing bypass? Since i know that i will always pass appropriate name to method... Unless the rule of thumb is to create method for each variable?
Normally you would use a collection like a Map.
public class Storage{
private final Map<String, Integer> inventory = ...
public void addCount(String key, int count) {
Integer i = inventory.get(key);
if (i == null) i = 0;
inventory.put(key, i + count);
}
I guess that by using reflection you can iterate through the fields/methods of your object and do your computation.
For one specific field:
Field member = myObject.getClass().getField(fieldName);
// If you know the class: Field member = MyClass.class.getField(fieldName);
System.out.println(member.getInt(myObject)); // Get the value
member.setInt(myObject, 4); // Set the value
If you want to something for all the public members:
for(Field member: myObject.getClass().getFields())
// Or you can do: for(Field member: myClass.class.getFields())
{
member.getInt(myObject)); // Get the value
member.setInt(myObject, 4); // Set the value
}
Basically, what you do is that you find the Field object that represents the members of you object, then you can manipulate it.
Most IDEs will generate setters and getters for you. This will do what you want with no bother or effort. If this is insufficient, write a method which uses reflection to set the values.
If you have a class with 15000 members, and by this I assume you mean variables private to a class, then you have other issues to resolve.