Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

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

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**
     * Get a list of the name of variables of the class received
     * @param klass Class to get the variable names
     * @return List<String>[] of length 3 with variable names: [0]: primitives, [1]: arrays, [2]: objects
     */
    public static List<String>[] getVariableNames(Class klass) {

        //array to return
        List<String>[] varNames = new List[3];
        for (int i = 0; i < 3; i++) {
            varNames[i] = new ArrayList<>();
        }

        //add all valid fields
        do {
            Field[] fields = klass.getDeclaredFields();
            for (Field field : fields) {
                if (!Modifier.isTransient(field.getModifiers())) {

                    //get the type
                    Class type = field.getType();

                    if (type.isPrimitive() || (type == Integer.class) || (type == Float.class)
                            || (type == Double.class) || (type == Boolean.class) || (type == String.class)) {
                        varNames[0].add(field.getName());
                    } else if (type.isArray()) {
                        varNames[1].add(field.getName());
                    } else {
                        varNames[2].add(field.getName());
                    }
                }
            }

            klass = klass.getSuperclass();
        } while (klass != null);

        //return array
        return varNames;

    }
}