Fayaz Ahammed
Fayaz Ahammed

Reputation: 1

Variables count in an Object

I have one simple question, Where we need the count of the variables in an Object:

class cot{ int I; int j; int k; }

We need the count of the variables (3) for each iteration on cot[], we have size() which we can use for getting size of Array List of Object. But how to find the count of the Variables for each Iteration on the Object.

We know it is three , But need for dynamic Objects.

Upvotes: 0

Views: 100

Answers (2)

ArcticLord
ArcticLord

Reputation: 4039

You can use Reflection API. Here is an example:

import java.lang.reflect.Field;

public class cot{
    int I; int j; int k;
    String str;

    public int CountAllVariables(){
        // get reference to own class
        Class<?> clazz = this.getClass();
        // return amount of all fields
        return clazz.getDeclaredFields().length;
    }
    public int CountAllInteger(){
        int result = 0;
        // get reference to own class
        Class<?> clazz = this.getClass();
        // check all fields
        for ( Field field : clazz.getDeclaredFields() ) {
            // count if it is an int field
            if(int.class.isAssignableFrom(field.getType()))
                result++;
        }
        return result;
    }
}

Now you can use it like this:

public static void main(String[] args){
    cot c = new cot();
    System.out.println( c.CountAllInteger());    // prints 3
    System.out.println( c.CountAllVariables());  // prints 4
}

Upvotes: 1

neza
neza

Reputation: 124

With reflection: MyClass.class.getFields().length

Check this for more information.

Upvotes: 0

Related Questions