Example usage for java.lang Class getDeclaredField

List of usage examples for java.lang Class getDeclaredField

Introduction

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

Prototype

@CallerSensitive
public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.

Usage

From source file:Main.java

public static void main(String[] args) {

    try {//from  ww w.j  a v  a  2  s  . c o m
        MyClass c = new MyClass();
        Class cls = c.getClass();

        Field lVal = cls.getDeclaredField("l");
        System.out.println("Field = " + lVal.toString());
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

From source file:Main.java

public static void main(String... args) {
    Main ft = new Main();
    try {/*from  w  w  w  .j  av  a2  s.c  o  m*/
        Class<?> c = ft.getClass();
        Field f = c.getDeclaredField("b");
        f.setAccessible(true); // solution
        f.setBoolean(ft, Boolean.FALSE); // IllegalAccessException

        // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalArgumentException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:FieldTroubleToo.java

public static void main(String... args) {
    FieldTroubleToo ft = new FieldTroubleToo();
    try {//  w w  w .j a va2  s. c o m
        Class<?> c = ft.getClass();
        Field f = c.getDeclaredField("b");
        // f.setAccessible(true); // solution
        f.setBoolean(ft, Boolean.FALSE); // IllegalAccessException

        // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalArgumentException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:TraceLevel.java

public static void main(String... args) {
    TraceLevel newLevel = TraceLevel.valueOf(args[0]);

    try {// w  w w.j  av a2  s. c  om
        MyServer svr = new MyServer();
        Class<?> c = svr.getClass();
        Field f = c.getDeclaredField("level");
        f.setAccessible(true);
        TraceLevel oldLevel = (TraceLevel) f.get(svr);
        out.format("Original trace level:  %s%n", oldLevel);

        if (oldLevel != newLevel) {
            f.set(svr, newLevel);
            out.format("    New  trace level:  %s%n", f.get(svr));
        }

        // production code should handle these exceptions more gracefully
    } catch (IllegalArgumentException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    }
}

From source file:Tweedle.java

public static void main(String... args) {
    Book book = new Book();
    String fmt = "%6S:  %-12s = %s%n";

    try {/*from  ww  w . ja  va 2 s. co m*/
        Class<?> c = book.getClass();

        Field chap = c.getDeclaredField("chapters");
        out.format(fmt, "before", "chapters", book.chapters);
        chap.setLong(book, 12);
        out.format(fmt, "after", "chapters", chap.getLong(book));

        Field chars = c.getDeclaredField("characters");
        out.format(fmt, "before", "characters", Arrays.asList(book.characters));
        String[] newChars = { "Queen", "King" };
        chars.set(book, newChars);
        out.format(fmt, "after", "characters", Arrays.asList(book.characters));

        Field t = c.getDeclaredField("twin");
        out.format(fmt, "before", "twin", book.twin);
        t.set(book, Tweedle.DUM);
        out.format(fmt, "after", "twin", t.get(book));

        // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:MyClass.java

public static void main(String[] args) {
    Class<MyClass> my = MyClass.class;
    try {/*  www  .  j av  a2  s.co m*/
        MyClass p = my.newInstance();
        Field nameField = my.getDeclaredField("name");
        nameField.setAccessible(true);
        String nameValue = (String) nameField.get(p);
        System.out.println("Current name is " + nameValue);
        nameField.set(p, "abc");
        nameValue = (String) nameField.get(p);
        System.out.println("New name is " + nameValue);
    } catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
            | IllegalArgumentException e) {
        System.out.println(e.getMessage());
    }
}

From source file:GrowBufferedReader.java

public static void main(String... args) {
    try {/* w w w.  j  av a2 s  . c om*/
        BufferedReader br = new BufferedReader(car);

        Class<?> c = br.getClass();
        Field f = c.getDeclaredField("cb");

        // cb is a private field
        f.setAccessible(true);
        char[] cbVal = char[].class.cast(f.get(br));

        char[] newVal = Arrays.copyOf(cbVal, cbVal.length * 2);
        if (args.length > 0 && args[0].equals("grow"))
            f.set(br, newVal);

        for (int i = 0; i < srcBufSize; i++)
            br.read();

        // see if the new backing array is being used
        if (newVal[srcBufSize - 1] == src[srcBufSize - 1])
            out.format("Using new backing array, size=%d%n", newVal.length);
        else
            out.format("Using original backing array, size=%d%n", cbVal.length);

        // production code should handle these exceptions more gracefully
    } catch (FileNotFoundException x) {
        x.printStackTrace();
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (IOException x) {
        x.printStackTrace();
    }
}

From source file:at.tuwien.ifs.somtoolbox.doc.RunnablesReferenceCreator.java

public static void main(String[] args) {
    ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class,
            true);//from  w ww .j  av a 2  s . com
    Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR);

    StringBuilder sbIndex = new StringBuilder(runnables.size() * 50);
    StringBuilder sbDetails = new StringBuilder(runnables.size() * 200);

    sbIndex.append("\n<table border=\"0\">\n");

    Type lastType = null;

    for (Class<? extends SOMToolboxApp> c : runnables) {
        try {
            // Ignore abstract classes and interfaces
            if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
                continue;
            }

            Type type = Type.getType(c);
            if (type != lastType) {
                sbIndex.append("  <tr> <td colspan=\"2\"> <h5> " + type + " Applications </h5> </td> </tr>\n");
                sbDetails.append("<h2> " + type + " Applications </h2>\n");
                lastType = type;
            }
            String descr = "N/A";
            try {
                descr = (String) c.getDeclaredField("DESCRIPTION").get(null);
            } catch (Exception e) {
            }
            String longDescr = "descr";
            try {
                longDescr = (String) c.getDeclaredField("LONG_DESCRIPTION").get(null);
            } catch (Exception e) {
            }

            sbIndex.append("  <tr>\n");
            sbIndex.append("    <td> <a href=\"#").append(c.getSimpleName()).append("\">")
                    .append(c.getSimpleName()).append("</a> </td>\n");
            sbIndex.append("    <td> ").append(descr).append(" </td>\n");
            sbIndex.append("  </tr>\n");

            sbDetails.append("<h3 id=\"").append(c.getSimpleName()).append("\">").append(c.getSimpleName())
                    .append("</h3>\n");
            sbDetails.append("<p>").append(longDescr).append("</p>\n");

            try {
                Parameter[] options = (Parameter[]) c.getField("OPTIONS").get(null);
                JSAP jsap = AbstractOptionFactory.registerOptions(options);
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(os);
                AbstractOptionFactory.printHelp(jsap, c.getName(), ps);
                sbDetails.append("<pre>").append(StringEscapeUtils.escapeHtml(os.toString())).append("</pre>");
            } catch (Exception e1) { // we didn't find the options => let the class be invoked ...
            }

        } catch (SecurityException e) {
            // Should not happen - no Security
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    sbIndex.append("</table>\n\n");
    System.out.println(sbIndex);
    System.out.println(sbDetails);
}

From source file:Main.java

public static int getId(String resourceName, Class<?> c) {
    try {//from ww w .  java  2s . c  o  m
        Field idField = c.getDeclaredField(resourceName);
        return idField.getInt(idField);
    } catch (Exception e) {
        throw new RuntimeException("No resource ID found for: " + resourceName + " / " + c, e);
    }
}

From source file:Main.java

public static Field getPrivateField(Object target, String fieldName) throws NoSuchFieldException {
    Class targetClass = target.getClass();
    Field field = targetClass.getDeclaredField(fieldName);
    field.setAccessible(true);//www . j  a v  a 2 s. c om
    return field;
}