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:br.edu.ifes.bd2dao.cgt.Menu.java

private Object scanSpecific(String fieldName, Scanner sc, Class c) throws NoSuchFieldException {

    Field field = c.getDeclaredField(fieldName);
    boolean valid = false;
    Object value = null;//from  w  w w .j a v a2 s.  c om

    while (!valid) {
        System.out.println(this.messages.get(fieldName.toUpperCase()));
        String type = field.getType().getSimpleName();

        switch (type.toUpperCase()) {
        case "STRING":
            value = sc.nextLine();
            valid = true;
            break;
        case "GENERO":
            String genero = sc.nextLine().toUpperCase();
            valid = Genero.exists(genero);
            if (valid)
                value = Genero.valueOf(genero);
            break;
        case "CALENDAR":
            String date = sc.nextLine();
            valid = this.dateValidator.validate(date);
            if (valid)
                value = convertStringToCalendar(date);
            break;
        case "INT":
            value = sc.nextInt();
            valid = true;
            break;
        }
    }

    return value;
}

From source file:ru.portal.services.TableServiceImpl.java

/**
 * TODO    ManyToMany/*  w  w w .j a va 2s  .  co m*/
 * @param entityClass
 * @param id
 * @return 
 */
@Override
public Map<EntityType<?>, Map<String, String>> findByEntityClassId(String entityClass, String id) {

    try {
        Class<?> cl = Class.forName(entityClass);
        EntityType<?> entityType = em.getEntityManagerFactory().getMetamodel().entity(cl);
        if (entityType != null && entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(entityClass)) {
                Class<?> bindableJavaType = entityType.getBindableJavaType();
                //select

                CriteriaBuilder cb = em.getCriteriaBuilder();
                CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
                Root<?> root = cq.from(User.class);

                cq.where(cb.equal(root.get("id"), Long.parseLong(id)));

                TypedQuery<?> query = em.createQuery(cq);
                ParameterExpression<Long> parameter = cb.parameter(Long.class, "id");
                //query.setParameter(parameter, Long.parseLong(id));
                //query.unwrap(org.hibernate.Query.class).getQueryString();

                Object result = query.getSingleResult();

                List<String> columns = getTableOrViewMetaData(entityClass);

                HashMap<String, String> res = new HashMap<>(columns.size());
                Class<? extends Object> clazz = result.getClass();
                for (String fieldName : columns) {
                    try {
                        Field field = clazz.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        Object fieldValue = field.get(result);
                        res.put(fieldName, fieldValue.toString());
                    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                            | IllegalAccessException ex) {
                        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                System.out.println(res);
                Map<EntityType<?>, Map<String, String>> hm = new HashMap<>();
                hm.put(entityType, res);
                return hm;

            }
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:ru.portal.services.TableServiceImpl.java

@Override
public Page<HashMap<String, String>> findAll(String tableOrViewName, Pageable pageable) {

    List<HashMap<String, String>> result = new ArrayList<>();

    EntityType<?> type = null;/* w w w. j  ava 2s. co  m*/
    Set<EntityType<?>> set = em.getEntityManagerFactory().getMetamodel().getEntities();
    for (EntityType<?> entityType : set) {
        if (entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(tableOrViewName)) {
                type = entityType;
                break;
            }
        }
    }

    Long totalRows = 0L;

    if (type != null) {
        Class<?> bindableJavaType = type.getBindableJavaType();

        //count
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
        countQuery.select(criteriaBuilder.count(countQuery.from(bindableJavaType)));
        totalRows = em.createQuery(countQuery).getSingleResult();

        //select
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
        Root<?> root = cq.from(bindableJavaType);
        //          cq.select(root);
        if (pageable == null) {
            pageable = new PageRequest(0, 50);
        }

        TypedQuery<?> query = em.createQuery(cq);

        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<?> all = query.getResultList();

        List<String> columns = getTableOrViewMetaData(tableOrViewName);

        for (Object object : all) {

            HashMap<String, String> res = new HashMap<>(columns.size());
            Class<? extends Object> clazz = object.getClass();
            for (String fieldName : columns) {
                try {
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    Object fieldValue = field.get(object);
                    res.put(fieldName, fieldValue.toString());
                    //TODO cast data integer long etc
                } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                        | IllegalAccessException ex) {
                    Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            result.add(res);
        }
    }

    PageImpl<HashMap<String, String>> list = new PageImpl<>(result, pageable, totalRows);
    return list;
}

From source file:com.db2eshop.util.orm.TableValueEntityResolver.java

/**
 * <p>asTableData.</p>/*w w  w. ja v  a  2 s. co m*/
 *
 * @param entity a {@link com.db2eshop.model.support.AbstractModel} object.
 * @param fields an array of {@link java.lang.String} objects.
 * @return an array of {@link java.lang.Object} objects.
 */
public Object[] asTableData(AbstractModel<?> entity, String[] fields) {
    if (entity == null) {
        throw new RuntimeException("Entity cannot be null");
    }
    if (fields == null) {
        throw new RuntimeException("Entity extraction fields cannot be null");
    }

    Object[] data = new Object[fields.length];
    int index = 0;
    Class<?> entityClass = entity.getClass();
    for (String field : fields) {
        try {
            Object object = ClassUtil.getValueOf(field, entity, entityClass,
                    entityClass.getDeclaredField(field).getType());
            data[index] = object;
        } catch (Exception e) {
            log.error("Field " + field + " could not been found", e);
            data[index] = e.getMessage();
        }
        index++;
    }
    return data;
}

From source file:com.orange.clara.cloud.servicedbdumper.task.boot.sequences.BootSequenceSecurity.java

public void removeEncryptionRestriction() {
    if (!isRestrictedCryptography()) {
        logger.info("Cryptography restrictions removal not needed");
        return;/*from   w  ww. j ava  2 s  . c om*/
    }
    try {
        /*
         * Do the following, but with reflection to bypass access checks:
         *
         * JceSecurity.isRestricted = false;
         * JceSecurity.defaultPolicy.perms.clear();
         * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
         */
        final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
        final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
        final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");

        final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
        isRestrictedField.setAccessible(true);
        final Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
        isRestrictedField.set(null, false);

        final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
        defaultPolicyField.setAccessible(true);
        final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);

        final Field perms = cryptoPermissions.getDeclaredField("perms");
        perms.setAccessible(true);
        ((Map<?, ?>) perms.get(defaultPolicy)).clear();

        final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
        instance.setAccessible(true);
        defaultPolicy.add((Permission) instance.get(null));

        logger.info("Successfully removed cryptography restrictions");
    } catch (final Exception e) {
        logger.warn("Failed to remove cryptography restrictions", e);
    }
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

public static <T> T createSAMLObject(final Class<T> clazz) throws NoSuchFieldException, IllegalAccessException {
    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    QName defaultElementName = (QName) clazz.getDeclaredField("DEFAULT_ELEMENT_NAME").get(null);
    XMLObjectBuilder builder = builderFactory.getBuilder(defaultElementName);
    T object = (T) builder.buildObject(defaultElementName);

    return object;
}

From source file:eu.crisis_economics.abm.dashboard.AvailableParameter.java

public AvailableParameter(final ParameterInfo info, final Class<?> modelClass) {
    if (info == null)
        throw new IllegalArgumentException("AvailableParameter(): null parameter.");

    this.info = info;

    Class<?> parentClass = modelClass;
    if (info.isSubmodelParameter()) {
        parentClass = ((ISubmodelGUIInfo) info).getParentValue();
    }/*from  w w w  .j av a 2s .c om*/

    Field declaredField = null;
    while (declaredField == null) {
        try {
            declaredField = parentClass.getDeclaredField(StringUtils.uncapitalize(info.getName()));
        } catch (NoSuchFieldException e) {
            parentClass = parentClass.getSuperclass();

            if (parentClass == null) {
                //               throw new IllegalStateException("Could not find field for parameter " + info.getName() + " in " + startClass);
                break;
            }
        }
    }

    if (declaredField != null) {
        for (final Annotation element : declaredField.getAnnotations()) {
            if (element.annotationType().getName() != Layout.class.getName()) // Proxies
                continue;

            final Class<? extends Annotation> type = element.annotationType();

            try {
                displayName = (String) (type.getMethod("FieldName").invoke(element));
            } catch (IllegalArgumentException e) {
            } catch (SecurityException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            } catch (NoSuchMethodException e) {
            }
        }
    }

    if (displayName == null) {
        displayName = info.getName().replaceAll("([A-Z])", " $1");
    }
}

From source file:com.ppp.prm.portal.server.service.gwt.HibernateDetachUtility.java

private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields,
        Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth,
        SerializationType serializationType) throws Exception {

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;//from   w  w  w  .java 2 s.  c  o m
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (!replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof org.hibernate.collection.PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((org.hibernate.collection.PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("com.ppp")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}

From source file:ch.flashcard.HibernateDetachUtility.java

private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields,
        Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth,
        SerializationType serializationType) throws Exception {

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;/*from   ww  w.  ja v  a 2 s  . co  m*/
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (replacement != null && !replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("org.rhq")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}

From source file:io.neba.core.util.ReflectionUtilTest.java

private void withField(Class<?> type, String name) throws NoSuchFieldException {
    this.field = type.getDeclaredField(name);
}