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:grails.util.GrailsClassUtils.java

/**
 * <p>Work out if the specified property is readable and static. Java introspection does not
 * recognize this concept of static properties but Groovy does. We also consider public static fields
 * as static properties with no getters/setters</p>
 *
 * @param clazz The class to check for static property
 * @param propertyName The property name
 * @return true if the property with name propertyName has a static getter method
 *//*from   w  w  w . j a v a2s .  c om*/
@SuppressWarnings("rawtypes")
public static boolean isStaticProperty(Class clazz, String propertyName) {
    Method getter = BeanUtils.findDeclaredMethod(clazz, getGetterName(propertyName), (Class[]) null);
    if (getter != null) {
        return isPublicStatic(getter);
    }

    try {
        Field f = clazz.getDeclaredField(propertyName);
        if (f != null) {
            return isPublicStatic(f);
        }
    } catch (NoSuchFieldException ignored) {
        // ignored
    }

    return false;
}

From source file:io.cloudslang.lang.cli.services.ConsolePrinterImplTest.java

@Test
public void testNullPointerExceptionNotThrown() throws NoSuchFieldException, IllegalAccessException {
    ConsolePrinterImpl consolePrinter = new ConsolePrinterImpl();
    consolePrinter.initialize();//from  w w w . jav  a  2  s . c om

    Class<? extends ConsolePrinterImpl> consolePrinterClass = consolePrinter.getClass();
    Field consolePrinterClassDeclaredField = consolePrinterClass.getDeclaredField(LAST_TASK);

    consolePrinterClassDeclaredField.setAccessible(true);
    Object lastTask = consolePrinterClassDeclaredField.get(consolePrinter);
    assertNull(lastTask);

    consolePrinter.waitForAllPrintTasksToFinish();
}

From source file:com.agimatec.validation.util.PropertyAccess.java

public Type getJavaType() {
    /*if(Map.class.isAssignableFrom(beanClass)) {
    return beanClass. /*w w w .jav a  2  s .c o m*/
    }*/
    if (rememberField != null) { // use cached field of previous access
        return rememberField.getGenericType();
    }
    for (PropertyDescriptor each : PropertyUtils.getPropertyDescriptors(beanClass)) {
        if (each.getName().equals(propertyName) && each.getReadMethod() != null) {
            return each.getReadMethod().getGenericReturnType();
        }
    }
    try { // try public field
        return beanClass.getField(propertyName).getGenericType();
    } catch (NoSuchFieldException ex2) {
        // search for private/protected field up the hierarchy
        Class theClass = beanClass;
        while (theClass != null) {
            try {
                return theClass.getDeclaredField(propertyName).getGenericType();
            } catch (NoSuchFieldException ex3) {
                // do nothing
            }
            theClass = theClass.getSuperclass();
        }
    }
    return Object.class; // unknown type: allow any type?? 
}

From source file:io.cloudslang.lang.cli.services.ConsolePrinterImplTest.java

@Test
public void testDestroy() throws Exception {
    ConsolePrinterImpl consolePrinter = new ConsolePrinterImpl();
    consolePrinter.initialize();/*from w w w  . j  av a2  s  .  com*/

    Class<? extends ConsolePrinterImpl> consolePrinterClass = consolePrinter.getClass();
    Field consolePrinterClassDeclaredField = consolePrinterClass.getDeclaredField(SINGLE_THREAD_EXECUTOR);

    consolePrinterClassDeclaredField.setAccessible(true);
    Object singleThreadExecutor = consolePrinterClassDeclaredField.get(consolePrinter);
    assertNotNull(singleThreadExecutor);

    consolePrinter.destroy();

    singleThreadExecutor = consolePrinterClassDeclaredField.get(consolePrinter);
    assertNull(singleThreadExecutor);
}

From source file:edu.syr.pcpratts.rootbeer.runtime.Serializer.java

public Object readStaticField(Class cls, String name) {
    while (true) {
        try {/*  ww w  .  j  a v a 2 s  . c  o m*/
            Field f = cls.getDeclaredField(name);
            f.setAccessible(true);
            Object ret = f.get(null);
            return ret;
        } catch (Exception ex) {
            cls = cls.getSuperclass();
        }
    }
}

From source file:edu.usu.sdl.openstorefront.core.sort.BeanComparator.java

@Override
public int compare(T o1, T o2) {
    T obj1 = o1;/*from   w w  w. ja  v a  2  s.  c o m*/
    T obj2 = o2;
    if (OpenStorefrontConstant.SORT_ASCENDING.equals(sortDirection)) {
        obj1 = o2;
        obj2 = o1;
    }

    if (obj1 != null && obj2 == null) {
        return 1;
    } else if (obj1 == null && obj2 != null) {
        return -1;
    } else if (obj1 != null && obj2 != null) {
        if (StringUtils.isNotBlank(sortField)) {
            try {
                Object o = obj1;
                Class<?> c = o.getClass();

                Field f = c.getDeclaredField(sortField);
                f.setAccessible(true);
                if (f.get(o) instanceof Date) {
                    int compare = 0;
                    DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
                    if (BeanUtils.getProperty(obj1, sortField) != null
                            && BeanUtils.getProperty(obj2, sortField) == null) {
                        return 1;
                    } else if (BeanUtils.getProperty(obj1, sortField) == null
                            && BeanUtils.getProperty(obj2, sortField) != null) {
                        return -1;
                    } else if (BeanUtils.getProperty(obj1, sortField) != null
                            && BeanUtils.getProperty(obj2, sortField) != null) {
                        Date value1 = format.parse(BeanUtils.getProperty(obj1, sortField));
                        Date value2 = format.parse(BeanUtils.getProperty(obj2, sortField));
                        if (value1 != null && value2 == null) {
                            return 1;
                        } else if (value1 == null && value2 != null) {
                            return -1;
                        } else if (value1 != null && value2 != null) {

                            compare = value1.compareTo(value2);
                        }
                    }
                    return compare;
                } else {
                    try {
                        String value1 = BeanUtils.getProperty(obj1, sortField);
                        String value2 = BeanUtils.getProperty(obj2, sortField);
                        if (value1 != null && value2 == null) {
                            return 1;
                        } else if (value1 == null && value2 != null) {
                            return -1;
                        } else if (value1 != null && value2 != null) {

                            if (StringUtils.isNotBlank(value1) && StringUtils.isNotBlank(value2)
                                    && StringUtils.isNumeric(value1) && StringUtils.isNumeric(value2)) {

                                BigDecimal numValue1 = new BigDecimal(value1);
                                BigDecimal numValue2 = new BigDecimal(value2);
                                return numValue1.compareTo(numValue2);
                            } else {
                                return value1.toLowerCase().compareTo(value2.toLowerCase());
                            }
                        }
                    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                        log.log(Level.FINER, MessageFormat.format("Sort field doesn''t exist: {0}", sortField));
                    }
                }
            } catch (ParseException | NoSuchFieldException | SecurityException | IllegalArgumentException
                    | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                try {
                    String value1 = BeanUtils.getProperty(obj1, sortField);
                    String value2 = BeanUtils.getProperty(obj2, sortField);
                    if (value1 != null && value2 == null) {
                        return 1;
                    } else if (value1 == null && value2 != null) {
                        return -1;
                    } else if (value1 != null && value2 != null) {

                        if (StringUtils.isNotBlank(value1) && StringUtils.isNotBlank(value2)
                                && StringUtils.isNumeric(value1) && StringUtils.isNumeric(value2)) {

                            BigDecimal numValue1 = new BigDecimal(value1);
                            BigDecimal numValue2 = new BigDecimal(value2);
                            return numValue1.compareTo(numValue2);
                        } else {
                            return value1.toLowerCase().compareTo(value2.toLowerCase());
                        }
                    }
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex2) {
                    log.log(Level.FINER, MessageFormat.format("Sort field doesn''t exist: {0}", sortField));
                }
            }
        }
    }
    return 0;
}

From source file:org.elasticsearch.network.DirectBufferNetworkTests.java

/**
 * Validates that all the thread local allocated ByteBuffer in sun.nio under the Util$BufferCache
 * are not greater than 1mb.//  ww w.j  av  a2s.  co  m
 */
private void validateNoLargeDirectBufferAllocated() throws Exception {
    // Make the fields in the Thread class that store ThreadLocals
    // accessible
    Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
    threadLocalsField.setAccessible(true);
    // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
    // accessible
    Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
    Field tableField = tlmClass.getDeclaredField("table");
    tableField.setAccessible(true);

    for (Thread thread : Thread.getAllStackTraces().keySet()) {
        if (thread == null) {
            continue;
        }
        Object threadLocalMap = threadLocalsField.get(thread);
        if (threadLocalMap == null) {
            continue;
        }
        Object[] table = (Object[]) tableField.get(threadLocalMap);
        if (table == null) {
            continue;
        }
        for (Object entry : table) {
            if (entry == null) {
                continue;
            }
            Field valueField = entry.getClass().getDeclaredField("value");
            valueField.setAccessible(true);
            Object value = valueField.get(entry);
            if (value == null) {
                continue;
            }
            if (!value.getClass().getName().equals("sun.nio.ch.Util$BufferCache")) {
                continue;
            }
            Field buffersField = value.getClass().getDeclaredField("buffers");
            buffersField.setAccessible(true);
            Object[] buffers = (Object[]) buffersField.get(value);
            for (Object buffer : buffers) {
                if (buffer == null) {
                    continue;
                }
                assertThat(((ByteBuffer) buffer).capacity(), Matchers.lessThan(1 * 1024 * 1024));
            }
        }
    }

}

From source file:edu.syr.pcpratts.rootbeer.runtime.Serializer.java

public Object readField(Object base, String name) {
    Class cls = base.getClass();
    while (true) {
        try {//from   w  w w.ja va  2s. c  om
            Field f = cls.getDeclaredField(name);
            f.setAccessible(true);
            return f.get(base);
        } catch (Exception ex) {
            cls = cls.getSuperclass();
        }
    }
}

From source file:edu.syr.pcpratts.rootbeer.runtime.Serializer.java

public void writeField(Object base, String name, Object value) {
    Class cls = base.getClass();
    while (true) {
        try {//from  w  w  w . jav a2s . c o m
            Field f = cls.getDeclaredField(name);
            f.setAccessible(true);
            f.set(base, value);
            return;
        } catch (Exception ex) {
            cls = cls.getSuperclass();
        }
    }
}

From source file:com.app.server.util.ClassLoaderUtil.java

public static CopyOnWriteArrayList closeClassLoader(ClassLoader cl) {
    CopyOnWriteArrayList jars = new CopyOnWriteArrayList();
    boolean res = false;
    Class classURLClassLoader = null;
    if (cl instanceof URLClassLoader) {
        classURLClassLoader = URLClassLoader.class;
        if (cl instanceof WebClassLoader) {
            String url = "";
            CopyOnWriteArrayList webCLUrl = ((WebClassLoader) cl).geturlS();
            for (int index = 0; index < webCLUrl.size(); index++) {

                try {
                    url = ((URL) webCLUrl.get(index)).toURI().toString();
                } catch (URISyntaxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }/*from   w w w.ja  v  a2  s.c o m*/
                jars.add(url.replace("file:", "").replace("/", "\\").toUpperCase());
            }
        }
    } else if (cl instanceof VFSClassLoader) {
        classURLClassLoader = VFSClassLoader.class;
    }
    Field f = null;
    try {
        f = classURLClassLoader.getDeclaredField("ucp");
        //log.info(f);
    } catch (NoSuchFieldException e1) {
        // e1.printStackTrace();
        // log.info(e1.getMessage(), e1);

    }
    if (f != null) {
        f.setAccessible(true);
        Object obj = null;
        try {
            obj = f.get(cl);
        } catch (IllegalAccessException e1) {
            // e1.printStackTrace();
            // log.info(e1.getMessage(), e1);
        }
        if (obj != null) {
            final Object ucp = obj;
            f = null;
            try {
                f = ucp.getClass().getDeclaredField("loaders");
                //log.info(f);
            } catch (NoSuchFieldException e1) {
                // e1.printStackTrace();
                // log.info(e1.getMessage(), e1);
            }
            if (f != null) {
                f.setAccessible(true);
                ArrayList loaders = null;
                try {
                    loaders = (ArrayList) f.get(ucp);
                    res = true;
                } catch (IllegalAccessException e1) {
                    // e1.printStackTrace();
                }
                for (int i = 0; loaders != null && i < loaders.size(); i++) {
                    obj = loaders.get(i);
                    f = null;
                    try {
                        f = obj.getClass().getDeclaredField("jar");
                        // log.info(f);
                    } catch (NoSuchFieldException e) {
                        // e.printStackTrace();
                        // log.info(e.getMessage(), e);
                    }
                    if (f != null) {
                        f.setAccessible(true);
                        try {
                            obj = f.get(obj);
                        } catch (IllegalAccessException e1) {
                            // e1.printStackTrace();
                            // log.info(e1.getMessage(), e1);
                        }
                        if (obj instanceof JarFile) {
                            final JarFile jarFile = (JarFile) obj;
                            //log.info(jarFile.getName());
                            jars.add(jarFile.getName().replace("/", "\\").trim().toUpperCase());
                            // try {
                            // jarFile.getManifest().clear();
                            // } catch (IOException e) {
                            // // ignore
                            // }
                            try {
                                jarFile.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                                // ignore
                                // log.info(e.getMessage(), e);
                            }
                        }
                    }
                }
            }
        }
    }
    return jars;
}