Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

reflection - How might I count the number of int members defined for a Java class?

I have a class that stores a large number of int member variables, each defined as follows:

public final static int int1 = int1value;
public final static int int2 = int2value;
...
public final static int int106 = int106value;

There is a second class that needs to do a loop based on the number of ints in the first class. How would I go about adding a function to the first class to count these member variables?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How are you storing it? In an int[] array or a List<Integer> list I assume? That would be the most logical choice. You can then just get the number by intArray.length or intList.size().

Check the Sun tutorials to learn more about Arrays or Collections.

Those are all declared as public static final int fields? Why don't you just add the count as another public static final int field? You already know the count beforehand! Or it must be a 3rd party class which you can't change in any way. It should have been more clarified in the original question.

Anyway, you can also consider to grab reflection. Here's an SSCCE:

package com.stackoverflow.q2203203;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Test {

    public static final int i1 = 1;
    public static final int i2 = 2;
    public static final int i3 = 3;

    public static void main(String[] args) throws Exception {
        int count = 0;
        for (Field field : Test.class.getDeclaredFields()) {
            if (field.getType() == int.class) {
                int modifiers = field.getModifiers();
                if (Modifier.isPublic(modifiers)
                    && Modifier.isStatic(modifiers)
                    && Modifier.isFinal(modifiers))
                {
                    count++;
                }
            }
        }
        System.out.println(count); // 3
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...