Example usage for java.lang Class getDeclaredFields

List of usage examples for java.lang Class getDeclaredFields

Introduction

In this page you can find the example usage for java.lang Class getDeclaredFields.

Prototype

@CallerSensitive
public Field[] getDeclaredFields() throws SecurityException 

Source Link

Document

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

Usage

From source file:RectangleFields.java

public static void main(String args[]) {
    Class rectClass = null;
    Field rectField[] = null;//from w  w  w. j a  v a 2  s  .  c  o m

    try {
        rectClass = Class.forName("java.awt.Rectangle");
        rectField = rectClass.getDeclaredFields();
    } catch (SecurityException se) {
        System.out.println("Access to Rectangle fields denied");
    } catch (ClassNotFoundException cnfe) {
        System.out.println("Didn't find the Rectangle class");
    }

    System.out.println("Fields in Rectangle are:");
    for (int i = 0; i < rectField.length; i++) {
        System.out.println(rectField[i].toString());
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    GetFields object = new GetFields();
    Class clazz = object.getClass();

    // Get all object fields including public, protected, package and private
    // access fields.
    Field[] fields = clazz.getDeclaredFields();
    System.out.println("Number of fields = " + fields.length);
    for (Field field : fields) {
        System.out.println("Field name = " + field.getName());
        System.out.println("Field type = " + field.getType().getName());
    }/*from   ww w  .  j  a  v a  2 s  .  c om*/

}

From source file:Spy.java

public static void main(String... args) {
    try {//  ww  w. j a  v a2  s  .c o m
        Class<?> c = Class.forName(args[0]);
        int searchMods = 0x0;
        for (int i = 1; i < args.length; i++) {
            searchMods |= modifierFromString(args[i]);
        }

        Field[] flds = c.getDeclaredFields();
        out.format("Fields in Class '%s' containing modifiers:  %s%n", c.getName(),
                Modifier.toString(searchMods));
        boolean found = false;
        for (Field f : flds) {
            int foundMods = f.getModifiers();
            // Require all of the requested modifiers to be present
            if ((foundMods & searchMods) == searchMods) {
                out.format("%-8s [ synthetic=%-5b enum_constant=%-5b ]%n", f.getName(), f.isSynthetic(),
                        f.isEnumConstant());
                found = true;
            }
        }

        if (!found) {
            out.format("No matching fields%n");
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:EnumSpy.java

public static void main(String... args) {
    try {/*from  w  ww  . j  av a  2 s .  c  o m*/
        Class<?> c = Class.forName(args[0]);
        if (!c.isEnum()) {
            out.format("%s is not an enum type%n", c);
            return;
        }
        out.format("Class:  %s%n", c);

        Field[] flds = c.getDeclaredFields();
        List<Field> cst = new ArrayList<Field>(); // enum constants
        List<Field> mbr = new ArrayList<Field>(); // member fields
        for (Field f : flds) {
            if (f.isEnumConstant())
                cst.add(f);
            else
                mbr.add(f);
        }
        if (!cst.isEmpty())
            print(cst, "Constant");
        if (!mbr.isEmpty())
            print(mbr, "Field");

        Constructor[] ctors = c.getDeclaredConstructors();
        for (Constructor ctor : ctors) {
            out.format(fmt, "Constructor", ctor.toGenericString(), synthetic(ctor));
        }

        Method[] mths = c.getDeclaredMethods();
        for (Method m : mths) {
            out.format(fmt, "Method", m.toGenericString(), synthetic(m));
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:org.syncope.hibernate.HibernateEnhancer.java

public static void main(final String[] args) throws Exception {

    if (args.length != 1) {
        throw new IllegalArgumentException("Expecting classpath as single argument");
    }/*  w w  w .  ja va  2  s . co  m*/

    ClassPool classPool = ClassPool.getDefault();
    classPool.appendClassPath(args[0]);

    PathMatchingResourcePatternResolver resResolver = new PathMatchingResourcePatternResolver(
            classPool.getClassLoader());
    CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();

    for (Resource resource : resResolver.getResources("classpath*:org/syncope/core/**/*.class")) {

        MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader(resource);
        if (metadataReader.getAnnotationMetadata().isAnnotated(Entity.class.getName())) {

            Class entity = Class.forName(metadataReader.getClassMetadata().getClassName());
            classPool.appendClassPath(new ClassClassPath(entity));
            CtClass ctClass = ClassPool.getDefault().get(entity.getName());
            if (ctClass.isFrozen()) {
                ctClass.defrost();
            }
            ClassFile classFile = ctClass.getClassFile();
            ConstPool constPool = classFile.getConstPool();

            for (Field field : entity.getDeclaredFields()) {
                if (field.isAnnotationPresent(Lob.class)) {
                    AnnotationsAttribute typeAttr = new AnnotationsAttribute(constPool,
                            AnnotationsAttribute.visibleTag);
                    Annotation typeAnnot = new Annotation("org.hibernate.annotations.Type", constPool);
                    typeAnnot.addMemberValue("type",
                            new StringMemberValue("org.hibernate.type.StringClobType", constPool));
                    typeAttr.addAnnotation(typeAnnot);

                    CtField lobField = ctClass.getDeclaredField(field.getName());
                    lobField.getFieldInfo().addAttribute(typeAttr);
                }
            }

            ctClass.writeFile(args[0]);
        }
    }
}

From source file:ShowClass.java

public static void main(String[] args) throws ClassNotFoundException {
    Class aClass = Class.forName("javax.swing.JComponent");
    if (aClass.isInterface()) {
        System.out.print(Modifier.toString(aClass.getModifiers()) + " " + typeName(aClass));
    } else if (aClass.getSuperclass() != null) {
        System.out.print(Modifier.toString(aClass.getModifiers()) + " class " + typeName(aClass) + " extends "
                + typeName(aClass.getSuperclass()));
    } else {/*from  www.j  av a2s .c  o  m*/
        System.out.print(Modifier.toString(aClass.getModifiers()) + " class " + typeName(aClass));
    }

    Class[] interfaces = aClass.getInterfaces();
    if ((interfaces != null) && (interfaces.length > 0)) {
        if (aClass.isInterface())
            System.out.print(" extends ");
        else
            System.out.print(" implements ");
        for (int i = 0; i < interfaces.length; i++) {
            if (i > 0)
                System.out.print(", ");
            System.out.print(typeName(interfaces[i]));
        }
    }

    System.out.println(" {");

    Constructor[] constructors = aClass.getDeclaredConstructors();
    for (int i = 0; i < constructors.length; i++)
        printMethodOrConstructor(constructors[i]);

    Field[] fields = aClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++)
        printField(fields[i]);

    Method[] methods = aClass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++)
        printMethodOrConstructor(methods[i]);

    System.out.println("}");
}

From source file:ReflectClass.java

public static void main(String args[]) {
    Constructor cn[];/*from www .  j a  v a2 s  .c o  m*/
    Class cc[];
    Method mm[];
    Field ff[];
    Class c = null;
    Class supClass;
    String x, y, s1, s2, s3;
    Hashtable classRef = new Hashtable();

    if (args.length == 0) {
        System.out.println("Please specify a class name on the command line.");
        System.exit(1);
    }

    try {
        c = Class.forName(args[0]);
    } catch (ClassNotFoundException ee) {
        System.out.println("Couldn't find class '" + args[0] + "'");
        System.exit(1);
    }

    /*
     * Step 0: If our name contains dots we're in a package so put
     * that out first.
     */
    x = c.getName();
    if (x.lastIndexOf(".") != -1) {
        y = x.substring(0, x.lastIndexOf("."));
        System.out.println("package " + y + ";\n\r");
    }

    /*
     * Let's use the Reflection API to sift through what is
     * inside this class.
     *
     * Step 1: Collect referenced classes
     * This step is used so that I can regenerate the import statements.
     * It isn't strictly required of course, Java works just fine with
     * fully qualified object class names, but it looks better when you
     * use 'String' rather than 'java.lang.String' as the return type.
     */

    ff = c.getDeclaredFields();
    for (int i = 0; i < ff.length; i++) {
        x = tName(ff[i].getType().getName(), classRef);
    }

    cn = c.getDeclaredConstructors();
    for (int i = 0; i < cn.length; i++) {
        Class cx[] = cn[i].getParameterTypes();
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                x = tName(cx[j].getName(), classRef);
            }
        }
    }

    mm = c.getDeclaredMethods();
    for (int i = 0; i < mm.length; i++) {
        x = tName(mm[i].getReturnType().getName(), classRef);
        Class cx[] = mm[i].getParameterTypes();
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                x = tName(cx[j].getName(), classRef);
            }
        }
    }

    // Don't import ourselves ...
    classRef.remove(c.getName());

    /*
     * Step 2: Start class description generation, start by printing
     *  out the import statements.
     *
     * This is the line that goes 'public SomeClass extends Foo {'
     */
    for (Enumeration e = classRef.keys(); e.hasMoreElements();) {
        System.out.println("import " + e.nextElement() + ";");
    }
    System.out.println();

    /*
     * Step 3: Print the class or interface introducer. We use
     * a convienience method in Modifer to print the whole string.
     */
    int mod = c.getModifiers();
    System.out.print(Modifier.toString(mod));

    if (Modifier.isInterface(mod)) {
        System.out.print(" interface ");
    } else {
        System.out.print(" class ");
    }
    System.out.print(tName(c.getName(), null));

    supClass = c.getSuperclass();
    if (supClass != null) {
        System.out.print(" extends " + tName(supClass.getName(), classRef));
    }
    System.out.println(" {");

    /*
     * Step 4: Print out the fields (internal class members) that are declared
     * by this class.
     *
     * Fields are of the form [Modifiers] [Type] [Name] ;
     */

    System.out.println("\n\r/*\n\r * Field Definitions.\r\n */");
    for (int i = 0; i < ff.length; i++) {
        Class ctmp = ff[i].getType();
        int md = ff[i].getModifiers();

        System.out.println("    " + Modifier.toString(md) + " " + tName(ff[i].getType().getName(), null) + " "
                + ff[i].getName() + ";");
    }

    /*
     * Step 5: Print out the constructor declarations.
     *
     * We note the name of the class which is the 'name' for all
     * constructors. Also there is no type, so the definition is
     * simplye [Modifiers] ClassName ( [ Parameters ] ) { }
     *
     */
    System.out.println("\n\r/*\n\r * Declared Constructors. \n\r */");
    x = tName(c.getName(), null);
    for (int i = 0; i < cn.length; i++) {
        int md = cn[i].getModifiers();
        System.out.print("    " + Modifier.toString(md) + " " + x);

        Class cx[] = cn[i].getParameterTypes();
        System.out.print("( ");
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                System.out.print(tName(cx[j].getName(), null));
                if (j < (cx.length - 1))
                    System.out.print(", ");
            }
        }
        System.out.print(") ");
        System.out.println("{ ... }");
    }

    /*
     * Step 6: Print out the method declarations.
     *
     * Now methods have a name, a return type, and an optional
     * set of parameters so they are :
     *  [modifiers] [type] [name] ( [optional parameters] ) { }
     */
    System.out.println("\n\r/*\n\r * Declared Methods.\n\r */");
    for (int i = 0; i < mm.length; i++) {
        int md = mm[i].getModifiers();
        System.out.print("    " + Modifier.toString(md) + " " + tName(mm[i].getReturnType().getName(), null)
                + " " + mm[i].getName());

        Class cx[] = mm[i].getParameterTypes();
        System.out.print("( ");
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                System.out.print(tName(cx[j].getName(), classRef));
                if (j < (cx.length - 1))
                    System.out.print(", ");
            }
        }
        System.out.print(") ");
        System.out.println("{ ... }");
    }

    /*
     * Step 7: Print out the closing brace and we're done!
     */
    System.out.println("}");
}

From source file:Main.java

public static void printFields(Class cl) {
    Field[] fields = cl.getDeclaredFields();

    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];//from  ww  w  .  j  a v  a2  s  . c o  m
        Class type = f.getType();
        String name = f.getName();
        System.out.print(Modifier.toString(f.getModifiers()));
        System.out.println(" " + type.getName() + " " + name + ";");
    }
}

From source file:MySuperClass.java

public static ArrayList<String> getDeclaredFieldsList(Class c) {
    Field[] fields = c.getDeclaredFields();
    ArrayList<String> fieldsList = getFieldsDesciption(fields);
    return fieldsList;
}

From source file:Main.java

public static List<Field> getFields(Class<?> clazz) {
    return Arrays.asList(clazz.getDeclaredFields());
}