Printing All Variables Value from a Class

Printing all variables value from a class

From Implementing toString:

public String toString() {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");

result.append( this.getClass().getName() );
result.append( " Object {" );
result.append(newLine);

//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();

//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");

return result.toString();
}

Print all variables in a class? - Python

print db['han'].__dict__

How do I print out all the data of each object in a class?

You need a collection in order to be able to iterate over the elements. Right now you instantiate Friend objects without collection them. You could use a List e.g.

List<Friends> listOfFriends = new ArrayList<>();
listOfFriends.add(colin);
listOfFriends.add(sanger);
listOfFriends.add(paul);

and then you could do

for(Friends f : listOfFriends){
// print out stuff for every friend from the variable f
}

You should also stick to the naming conventions. Friends class should be Friend and so on.

Printing value of private variables of a class in a loop using member functions

The problem is that you're calling the setfee member function only for the first object in the array stu. And since the array stu was default initialized meaning its elements were also default initialized, the data member fee of each of those elements inside stu has an indeterminate value. So, calling showfee on the elements on which setfee was not called, is undefined behavior since for those elements fee has indeterminate value and you're printing the value inside showfee.

because I want to set the same fee amount for every student and then autoprint it in a file for every stu[] array variable.

To solve this and do what you said in the above quoted statement, you can ask the user for the fee inside the main and then pass the input as an argument to the setfee member function. For this we have to change setfee member function in such a way that it has an int parameter. Next, using a 2nd for loop we could print the fee of each of the elements inside stu using showfee member function. This is shown below:

#include<iostream>

class FEE
{
private:
int fee = 0; //use in-class initializer for built in type
public:
void setfee(int pfee)
{
fee = pfee;

}
void showfee()
{
std::cout<<"Monthly fee is "<<fee<<std::endl;
}
};

int main()
{
FEE stu[5]; //default initiailized array

int inputFee = 0;
for(int i=0;i<5;i++)
{
std::cout<<"Enter the monthly fee= ";
std::cin>>inputFee;

//call setfee passing the inputFee
stu[i].setfee(inputFee);

}
for(int i = 0; i<5; ++i)
{
stu[i].showfee();
}
}

Demo

Also, note that using a std::vector instead of built in array is also an option here.

Some of the changes that i made include:

  1. Added a parameter to the setfee member function.
  2. Used in-class initializer for the fee data member.
  3. The input fee is taken inside main which is then passed to the setfee member function for each of the element inside stu.
  4. The member function showfee is called for each of the element inside stu using the 2nd for loop.

Print all the values from another class

If you plan to print every property the Vehicle and including all of its sub/child class, you will need reflection especially the GetProperties() method. You can do the following to get entire property of a given class instance:

 obj.GetType().GetProperties()

The statement above will returns PropertyInfo which have two component that will be useful for our need, namely property Name and method called GetValue. The following is an example of using the reflection from inside the Vehicle class.

 using System;
using System.Reflection;
using System.Collections.Generic;

public class Vehicle
{
....
public string PrintVehicle()
{
List<string> lsProp = new List<string>();
foreach(PropertyInfo prop in this.GetType().GetProperties())
{
object propVal = prop.GetValue(this);
if(propVal != null)
{
string propString = string.Format("{0} : {1}",
prop.Name, propVal.ToString());
lsProp.Add(propString);
}
}
return string.Join("\n", lsProp);
}
....
}

Note:

  • There might be many caveats with reflection, so thread carefully. do test your code thoroughly afterward.

  • It uses ToString() to convert non-string values, but do be aware non-simple types may return object name instead (e.g. System.Collections.Generic.List1[System.String] if its a List of string).

  • You can use the method from another class, but you have to pass the Vehicle instance.

  • You can use it to override ToString() too.

  • If you dont want to use reflection, you could define the "printing" as virtual then override it on each subclasses, example:

       public class Vehicle
    {
    public string LPlate {get; set;}

    public virtual string PrintVehicle()
    {
    return "LPlate :" + LPlate;
    }
    }

    public class BusinessCar : Vehicle
    {
    public string CompanyN {get; set;}

    public override string PrintVehicle()
    {
    return base.PrintVehicle() + "\nCompanyN :" + CompanyN;
    }
    }

    public class Limousine : BusinessCar
    {
    public string Gadgets {get; set;}

    public override string PrintVehicle()
    {
    return base.PrintVehicle() + "\nGadgets :" + Gadgets;
    }
    }

Though the drawback is surely that you have to mention each property manually.

How to print all the instances of a class in python?

you could do the following, if I got you right :

Proposal

tmp = globals().copy()
print(tmp)

for k,v in tmp.items():
if isinstance(v, A):
print(k)

You must copy the global variable dictionary, because otherwise i will be changed with the first instantiation in the for-loop:

Result:

foo
bar
star

How to print values of an object in Java when you do not have the source code for the class?

You can get all fields by Class#getDeclaredFields(). Each returns a Field object of which you in turn can use the get() method to obtain the value. To get the values for non-public fields, you only need to set Field#setAccessible() to true.

So, in a nut:

ClassABC abc = new ClassABC();
for (Field field : abc.getClass().getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
Object value = field.get(abc);
System.out.printf("Field name: %s, Field value: %s%n", name, value);
}

See also:

  • Reflection tutorial


Related Topics



Leave a reply



Submit