0

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.

1
  • 2
    ... and before that re-think your design. Why do you need that? And just the number? How about their types? What about private fields? Inherited fields? And computed properties not backed by any fields? Commented Nov 24, 2015 at 11:27

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Check this for more information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.