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:org.jsonschema2pojo.integration.PropertiesIT.java

@Test
public void propertyNamesAreLowerCamelCase() throws Exception {
    ClassLoader resultsClassLoader = schemaRule
            .generateAndCompile("/schema/properties/propertiesAreUpperCamelCase.json", "com.example");
    Class<?> generatedType = resultsClassLoader.loadClass("com.example.UpperCase");

    Object instance = generatedType.newInstance();

    new PropertyDescriptor("property1", generatedType).getWriteMethod().invoke(instance, "1");
    new PropertyDescriptor("propertyTwo", generatedType).getWriteMethod().invoke(instance, 2);
    new PropertyDescriptor("propertyThreeWithSpace", generatedType).getWriteMethod().invoke(instance, "3");
    new PropertyDescriptor("propertyFour", generatedType).getWriteMethod().invoke(instance, "4");

    JsonNode jsonified = mapper.valueToTree(instance);

    assertNotNull(generatedType.getDeclaredField("property1"));
    assertNotNull(generatedType.getDeclaredField("propertyTwo"));
    assertNotNull(generatedType.getDeclaredField("propertyThreeWithSpace"));
    assertNotNull(generatedType.getDeclaredField("propertyFour"));

    assertThat(jsonified.has("Property1"), is(true));
    assertThat(jsonified.has("PropertyTwo"), is(true));
    assertThat(jsonified.has(" PropertyThreeWithSpace"), is(true));
    assertThat(jsonified.has("propertyFour"), is(true));
}

From source file:org.pmp.budgeto.app.SwaggerDispatcherConfigTest.java

@Test
public void springConf() throws Exception {

    Class<?> clazz = swaggerDispatcherConfig.getClass();
    Assertions.assertThat(clazz.getAnnotations()).hasSize(4);
    Assertions.assertThat(clazz.isAnnotationPresent(Configuration.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableWebMvc.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableSwagger.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(ComponentScan.class)).isTrue();
    Assertions.assertThat(clazz.getAnnotation(ComponentScan.class).basePackages())
            .containsExactly("com.ak.swaggerspringmvc.shared.app", "com.ak.spring3.music");

    Field fSpringSwaggerConfig = clazz.getDeclaredField("springSwaggerConfig");
    Assertions.assertThat(fSpringSwaggerConfig.getAnnotations()).hasSize(1);
    Assertions.assertThat(fSpringSwaggerConfig.isAnnotationPresent(Autowired.class)).isTrue();

    Method mCustomImplementation = clazz.getDeclaredMethod("customImplementation", new Class[] {});
    Assertions.assertThat(mCustomImplementation.getAnnotations()).hasSize(1);
    Assertions.assertThat(mCustomImplementation.getAnnotation(Bean.class)).isNotNull();
}

From source file:com.google.gdt.eclipse.designer.hosted.tdz.HostedModeSupport.java

public void dispose() {
    m_browserShell.dispose();//w w  w  .j a  v  a2  s . c  o m
    // dispose if initialized (may be not if Module loading failed)
    if (m_moduleSpaceHost != null) {
        m_moduleSpaceHost.getModuleSpace().dispose();
    }
    // dispose for project; if the same project used in another editor 
    // it would be added again by activating the project. 
    m_gwtSharedClassLoader.dispose(m_moduleDescription);
    m_logSupport.dispose();
    m_moduleSpaceHost = null;
    // clear static caches
    try {
        Class<?> clazz = m_gwtSharedClassLoader.loadClass("com.google.gwt.i18n.rebind.ClearStaticData");
        Method method = clazz.getDeclaredMethod("clear");
        method.setAccessible(true);
        method.invoke(null);
    } catch (Throwable e) {
    }
    try {
        Class<?> clazz = m_gwtSharedClassLoader
                .loadClass("com.google.gwt.uibinder.rebind.model.OwnerFieldClass");
        Field mapField = clazz.getDeclaredField("FIELD_CLASSES");
        mapField.setAccessible(true);
        Map<?, ?> map = (Map<?, ?>) mapField.get(null);
        map.clear();
    } catch (Throwable e) {
    }
}

From source file:module.workflow.presentationTier.actions.ProcessManagement.java

private Field getField(Class activityClass, String parameter) throws SecurityException, NoSuchFieldException {
    if (activityClass == null) {
        throw new NoSuchFieldException();
    }/* w ww .  j a  va2  s  . co m*/
    Field field;
    try {
        field = activityClass.getDeclaredField(parameter);
    } catch (final NoSuchFieldException ex) {
        field = null;
    }
    return field == null ? getField(activityClass.getSuperclass(), parameter) : field;
}

From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java

/**
 * ???????/*from  w  ww.j av  a  2 s.  c om*/
 * @param klass   ???klass?Class
 * @param filepath   ?
 * @param sizeThreshold   ??
 * @param isFileNameBaseTime   ????
 * @return bean
 */
public static <T> Object upload(HttpServletRequest request, Class<T> klass, String filepath, int sizeThreshold,
        boolean isFileNameBaseTime) throws Exception {
    FileItemFactory fileItemFactory = null;
    if (sizeThreshold > 0) {
        File repository = new File(filepath);
        fileItemFactory = new DiskFileItemFactory(sizeThreshold, repository);
    } else {
        fileItemFactory = new DiskFileItemFactory();
    }
    ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
    ServletRequestContext requestContext = new ServletRequestContext(request);
    T bean = null;
    if (klass != null) {
        bean = klass.newInstance();
    }
    // 
    if (ServletFileUpload.isMultipartContent(requestContext)) {
        File parentDir = new File(filepath);

        List<FileItem> fileItemList = upload.parseRequest(requestContext);
        for (int i = 0; i < fileItemList.size(); i++) {
            FileItem item = fileItemList.get(i);
            // ??
            if (item.isFormField()) {
                String paramName = item.getFieldName();
                String paramValue = item.getString("UTF-8");
                log.info("?" + paramName + "=" + paramValue);
                request.setAttribute(paramName, paramValue);
                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);

                        if (field != null) {
                            field.setAccessible(true);
                            Class type = field.getType();
                            if (type == Integer.TYPE) {
                                field.setInt(bean, Integer.valueOf(paramValue));
                            } else if (type == Double.TYPE) {
                                field.setDouble(bean, Double.valueOf(paramValue));
                            } else if (type == Float.TYPE) {
                                field.setFloat(bean, Float.valueOf(paramValue));
                            } else if (type == Boolean.TYPE) {
                                field.setBoolean(bean, Boolean.valueOf(paramValue));
                            } else if (type == Character.TYPE) {
                                field.setChar(bean, paramValue.charAt(0));
                            } else if (type == Long.TYPE) {
                                field.setLong(bean, Long.valueOf(paramValue));
                            } else if (type == Short.TYPE) {
                                field.setShort(bean, Short.valueOf(paramValue));
                            } else {
                                field.set(bean, paramValue);
                            }
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?" + paramName);
                    }
                }
            }
            // 
            else {
                // <input type='file' name='xxx'> xxx
                String paramName = item.getFieldName();
                log.info("?" + item.getSize());

                if (sizeThreshold > 0) {
                    if (item.getSize() > sizeThreshold)
                        continue;
                }
                String clientFileName = item.getName();
                int index = -1;
                // ?IE?
                if ((index = clientFileName.lastIndexOf("\\")) != -1) {
                    clientFileName = clientFileName.substring(index + 1);
                }
                if (clientFileName == null || "".equals(clientFileName))
                    continue;

                String filename = null;
                log.info("" + paramName + "\t??" + clientFileName);
                if (isFileNameBaseTime) {
                    filename = buildFileName(clientFileName);
                } else
                    filename = clientFileName;

                request.setAttribute(paramName, filename);

                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);
                        if (field != null) {
                            field.setAccessible(true);
                            field.set(bean, filename);
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?  " + paramName);
                        continue;
                    }
                }

                if (!parentDir.exists()) {
                    parentDir.mkdirs();
                }

                File newfile = new File(parentDir, filename);
                item.write(newfile);
                String serverPath = newfile.getPath();
                log.info("?" + serverPath);
            }
        }
    }
    return bean;
}

From source file:org.nuxeo.client.api.objects.Document.java

/**
 * This constructor is providing a way to create 'adapters' of a document. See
 * org.nuxeo.client.test.objects.DataSet in nuxeo-java-client-test.
 *
 * @since 1.0//from w w w. j  a v a  2  s  . c om
 * @param document the document to copy from the sub class.
 */
public Document(Document document) {
    super(ConstantsV1.ENTITY_TYPE_DOCUMENT);
    type = ConstantsV1.DEFAULT_DOC_TYPE;
    for (Field field : document.getClass().getDeclaredFields()) {
        if (!Modifier.isFinal(field.getModifiers())) {
            try {
                Class<?> superclass = this.getClass().getSuperclass();
                if (superclass.equals(NuxeoEntity.class)) {
                    throw new NuxeoClientException(
                            "You should never use this constructor unless you're using a subclass of Document");
                }
                superclass.getDeclaredField(field.getName()).set(this, field.get(document));
            } catch (NoSuchFieldException | IllegalAccessException reason) {
                throw new NuxeoClientException(reason);
            }
        }
    }
}

From source file:org.mybatisorm.annotation.handler.JoinHandler.java

private Hashtable<Set<Class<?>>, LinkedList<Field[]>> getRefMap(List<Field> fields) {
    Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
    List<Field> refFields = new ArrayList<Field>();
    TableHandler handler = null;/*w  w  w.  j av a2s  .  co  m*/
    for (Field field : fields) {
        Class<?> clazz = field.getType();
        if (!TableHandler.hasAnnotation(clazz))
            throw new AnnotationNotFoundException(
                    "The property class " + clazz.getName() + " has no @Table annotation.");
        classMap.put(clazz.getSimpleName(), clazz);

        handler = HandlerFactory.getHandler(clazz);
        refFields.addAll(handler.getReferenceFields());
    }

    Hashtable<Set<Class<?>>, LinkedList<Field[]>> refMap = new Hashtable<Set<Class<?>>, LinkedList<Field[]>>();
    for (Field field : refFields) {
        Class<?> clazz = field.getDeclaringClass();
        String[] ref = field.getAnnotation(Column.class).references().split("\\.");
        if (ref.length < 2)
            throw new InvalidAnnotationException(clazz.getSimpleName() + "." + field.getName()
                    + " has invalid references property in @Column annotation.");

        Class<?> refClazz = classMap.get(ref[0]);
        if (refClazz == null)
            continue;

        Set<Class<?>> pair = pair(clazz, refClazz);
        LinkedList<Field[]> list = refMap.get(pair);
        if (list == null) {
            list = new LinkedList<Field[]>();
            refMap.put(pair, list);
        }
        Field refField = null;
        try {
            refField = refClazz.getDeclaredField(ref[1]);
        } catch (Exception e) {
            throw new InvalidAnnotationException("The " + ref[0] + " class has no " + ref[1] + " property.");
        }
        list.add(new Field[] { refField, field });
    }
    return refMap;
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil.java

public Object getDestroyPacket() {
    Class<?> PacketPlayOutEntityDestroy = Util.getCraftClass("PacketPlayOutEntityDestroy");

    Object packet = null;//from  w ww . j  a v  a2s.  co  m
    try {
        packet = PacketPlayOutEntityDestroy.newInstance();
        Field a = PacketPlayOutEntityDestroy.getDeclaredField("a");
        a.setAccessible(true);
        a.set(packet, new int[] { this.id });
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }

    return packet;
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Find field.//from   ww w.ja v  a 2 s . com
 * 
 * @param clazz
 *          the clazz
 * @param fieldName
 *          the field name
 * @param throwException
 *          the throw exception
 * @return the field
 */
public static Field findField(Class<?> clazz, String fieldName, boolean throwException) {

    Field field = null;
    Class<?> superClazz = clazz.getSuperclass();
    try {
        field = clazz.getDeclaredField(fieldName);
    } catch (Exception e) {
        if (!throwException) {
            logger.error(e);
        }
        if (superClazz.equals(Object.class)) {
            throw new RuntimeException(e);
        }
    }

    if (field == null) {
        field = findField(superClazz, fieldName);
    }

    return field;
}

From source file:com.cloudera.sqoop.manager.OracleManager.java

/**
 * Get database type.//from  w ww  .  ja  va  2  s .  co  m
 * @param clazz         oracle class representing sql types
 * @param fieldName     field name
 * @return              value of database type constant
 */
private int getDatabaseType(Class clazz, String fieldName) {
    // Need to use reflection to extract constant values because the database
    // specific java libraries are not accessible in this context.
    int value = -1;
    try {
        java.lang.reflect.Field field = clazz.getDeclaredField(fieldName);
        value = field.getInt(null);
    } catch (NoSuchFieldException ex) {
        LOG.error("Could not retrieve value for field " + fieldName, ex);
    } catch (IllegalAccessException ex) {
        LOG.error("Could not retrieve value for field " + fieldName, ex);
    }
    return value;
}