Example usage for java.lang Class getFields

List of usage examples for java.lang Class getFields

Introduction

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

Prototype

@CallerSensitive
public Field[] getFields() throws SecurityException 

Source Link

Document

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

Usage

From source file:com.nabla.wapp.server.auth.AuthDatabase.java

public AuthDatabase(final String dbName, final ServletContext serverContext, final Class<?> roles,
        final String rootPassword) throws SQLException {
    super(dbName, serverContext);
    final Connection conn = this.getConnection();
    try {/*w  w  w.  ja v a2s  .c  om*/
        new UserManager(conn).initializeDatabase(new UserManager.IRoleListProvider() {
            @Override
            public Map<String, String[]> get() {
                final Map<String, String[]> rslt = new HashMap<String, String[]>();
                for (final Field field : roles.getFields()) {
                    if (!field.getType().getCanonicalName().equals(String.class.getName()))
                        continue;
                    try {
                        final String roleName = (String) field.get(null); // assume static
                        final IRole definition = field.getAnnotation(IRole.class);
                        if (definition == null) {
                            // privilege
                            rslt.put(roleName, null);
                        } else {
                            // role
                            rslt.put(roleName, definition.value());
                        }
                    } catch (final IllegalArgumentException e) {
                        if (log.isDebugEnabled())
                            log.debug("invalid field '" + field.getName() + "' as a role", e);
                    } catch (final IllegalAccessException e) {
                        if (log.isDebugEnabled())
                            log.debug("invalid field '" + field.getName() + "' as a role", e);
                    }
                }
                return rslt;
            }
        }, rootPassword);
    } finally {
        close(conn);
    }
}

From source file:io.selendroid.server.model.internal.execute_native.FindRId.java

@Override
public Object executeScript(JSONArray args) {
    Class rClazz;
    try {//from ww  w.j  a va2s.c  om
        rClazz = serverInstrumentation.getTargetContext().getClassLoader()
                .loadClass(serverInstrumentation.getTargetContext().getPackageName() + ".R$id");
    } catch (ClassNotFoundException e) {
        SelendroidLogger.error("Cannot find id", e);
        return "";
    }
    String using = null;
    try {
        using = args.getString(0);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    for (Field field : rClazz.getFields()) {
        if (field.getName().equalsIgnoreCase(using)) {
            try {
                return field.getInt(null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    return "";
}

From source file:edu.brown.api.BenchmarkConfig.java

@Override
public String toString() {
    Class<?> confClass = this.getClass();
    final Map<String, Object> m0 = new ListOrderedMap<String, Object>();
    final Map<String, Object> m1 = new ListOrderedMap<String, Object>();
    final Map<String, Object> m2 = new ListOrderedMap<String, Object>();

    for (Field f : confClass.getFields()) {
        String key = f.getName().toUpperCase();
        if (key.equalsIgnoreCase("hosts")) {
            m0.put("Number of Hosts", this.hosts.length);
            m0.put("Hosts", StringUtil.join("\n", this.hosts));
        } else if (key.equalsIgnoreCase("clients")) {
            m1.put("Number of Clients", this.clients.length);
            m1.put("Clients", StringUtil.join("\n", this.clients));
        } else if (key.equalsIgnoreCase("clientParameters") || key.equalsIgnoreCase("siteParameters")) {
            // Skip
        } else {/*from w w  w  . j av a  2 s .  com*/
            Object val = null;
            try {
                val = f.get(this);
                if (ClassUtil.isArray(val))
                    val = Arrays.toString((Object[]) val);
            } catch (IllegalAccessException ex) {
                val = ex.getMessage();
            }
            if ((val instanceof HStoreConf) == false)
                m2.put(key, val);
        }
    } // FOR
    return (StringUtil.formatMaps(m0, m1, this.clientParameters, this.siteParameters, m2));
}

From source file:org.gofleet.context.GoClassLoader.java

public Object load(String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Class<?> res = super.loadClass(name);
    Object result = res.newInstance();

    for (Field f : res.getFields()) {
        if (f.isAnnotationPresent(GoWired.class)) {
            final Class<?> type = f.getType();
            String fieldNameClass = type.getCanonicalName();

            Object parameter = null;
            // Check if we already loaded it
            if (this.elements.containsKey(fieldNameClass))
                parameter = this.elements.get(fieldNameClass);
            else {
                parameter = this.loadClass(fieldNameClass).newInstance();
                this.elements.put(fieldNameClass, parameter);
            }//www  .j av  a  2 s. c  o m
            String methodname = ("set" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1));

            try {
                Method m = res.getMethod(methodname, type);
                m.invoke(result, type.cast(parameter));
            } catch (Throwable ex) {
                LOG.error("Error loading field " + f.getName() + " in class " + res.getCanonicalName()
                        + ". Are you sure the field has a proper setter method? It should be: " + methodname,
                        ex);
            }
        }
    }

    return result;
}

From source file:io.wcm.tooling.netbeans.sightly.completion.classLookup.MemberLookupResolver.java

/**
 * Fallback used to load the methods from classloader
 *
 * @param clazzname//from  w ww  . j  a  v a2 s  .co m
 * @param variable
 * @return set with all methods, can be empty
 */
private Set<MemberLookupResult> getMethodsFromClassLoader(String clazzname, String variable) {
    final Set<MemberLookupResult> ret = new LinkedHashSet<>();
    try {
        Class clazz = classPath.getClassLoader(true).loadClass(clazzname);
        for (Method method : clazz.getMethods()) {
            if (method.getReturnType() != Void.TYPE && GETTER_PATTERN.matcher(method.getName()).matches()) {
                ret.add(new MemberLookupResult(variable, method.getName(), method.getReturnType().getName()));
            }
        }
        for (Field field : clazz.getFields()) {
            ret.add(new MemberLookupResult(variable, field.getName(), field.getType().getName()));
        }
    } catch (ClassNotFoundException cnfe) {
        LOGGER.log(Level.FINE, "Could not resolve class " + clazzname + "defined for variable " + variable,
                cnfe);
    }
    return ret;
}

From source file:com.facebook.stetho.json.ObjectMapper.java

private <T> T _convertFromJSONObject(JSONObject jsonObject, Class<T> type) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException, JSONException {
    Constructor<T> constructor = type.getDeclaredConstructor((Class[]) null);
    constructor.setAccessible(true);/*  w  w w.  j  av a 2s  .  com*/
    T instance = constructor.newInstance();
    Field[] fields = type.getFields();
    for (int i = 0; i < fields.length; ++i) {
        Field field = fields[i];
        Object value = jsonObject.opt(field.getName());
        Object setValue = getValueForField(field, value);
        try {
            field.set(instance, getValueForField(field, value));
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Class: " + type.getSimpleName() + " " + "Field: "
                    + field.getName() + " type " + setValue.getClass().getName(), e);
        }
    }
    return instance;
}

From source file:com.taobao.weex.devtools.json.ObjectMapper.java

private <T> T _convertFromJSONObject(JSONObject jsonObject, Class<T> type) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException, JSONException {
    Constructor<T> constructor = type.getDeclaredConstructor((Class[]) null);
    constructor.setAccessible(true);/*from  w ww . j  av a2s  .  c  om*/
    T instance = constructor.newInstance();
    Field[] fields = type.getFields();
    for (int i = 0; i < fields.length; ++i) {
        Field field = fields[i];
        Object value = jsonObject.opt(field.getName());
        Object setValue = getValueForField(field, value);
        try {
            field.set(instance, setValue);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Class: " + type.getSimpleName() + " " + "Field: "
                    + field.getName() + " type " + setValue.getClass().getName(), e);
        }
    }
    return instance;
}

From source file:org.hako.dao.mapper.AnnotationMapper.java

public EntityMeta setUp(Class<?> clazz) {
    if (!clazz.isAnnotationPresent(Entity.class)) {
        throw new IllegalArgumentException("class must with Entity annotation");
    }// w  w  w .j av a2 s  . c  o m
    Entity entityAnno = clazz.getAnnotation(Entity.class);
    String tableName = StringUtils.defaultIfBlank(entityAnno.tableName(), clazz.getSimpleName());
    String alias = StringUtils.defaultIfBlank(entityAnno.tableAlias(), tableName);
    EntityName entityName = new EntityName(tableName, alias);
    // setup fields
    List<FieldMeta> fields = new ArrayList<FieldMeta>();
    for (java.lang.reflect.Field f : clazz.getFields()) {
        if (f.isAnnotationPresent(Field.class)) {
            String propertyName = f.getName();
            Field fieldAnno = f.getAnnotation(Field.class);
            String columnName = StringUtils.defaultIfBlank(fieldAnno.columnName(),
                    toDashSeparated(propertyName));
            fields.add(new FieldMeta(columnName, propertyName, f.isAnnotationPresent(Id.class)));
        }
    }
    return new EntityMeta(entityName, fields);
}

From source file:org.zodiark.server.ZodiarkObjectFactory.java

@Override
public <T, U extends T> T newClassInstance(final AtmosphereFramework framework, Class<T> classType,
        Class<U> tClass) throws InstantiationException, IllegalAccessException {
    logger.debug("About to create {}", tClass.getName());
    if (!added.getAndSet(true) && framework != null) {
        framework.getAtmosphereConfig().shutdownHook(new AtmosphereConfig.ShutdownHook() {
            @Override//from   w  w w  .  jav  a 2s  .c  o m
            public void shutdown() {
                timer.shutdown();
            }
        });
        framework.getAtmosphereConfig().startupHook(new AtmosphereConfig.StartupHook() {

            @Override
            public void started(AtmosphereFramework framework) {
                injectRepository.clear();
                implementationRepository.clear();
                instanceRepository.clear();
            }
        });

    }

    Class<? extends T> impl = implement(classType);

    boolean needsPostConstruct = (impl == null || instanceRepository.get(impl) == null);
    T instance = impl != null ? newInstance(impl) : tClass.newInstance();

    Field[] fields = tClass.equals(instance.getClass()) ? tClass.getDeclaredFields() : impl.getFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(Inject.class)) {
            if (field.getType().isAssignableFrom(ObjectMapper.class)) {
                field.set(instance, inject(ObjectMapper.class));
            } else if (field.getType().isAssignableFrom(EventBus.class)) {
                field.set(instance, inject(EventBus.class));
            } else if (field.getType().isAssignableFrom(RestService.class)) {
                field.set(instance, newClassInstance(framework, RestService.class, RestService.class));
            } else if (field.getType().isAssignableFrom(WowzaEndpointManager.class)) {
                field.set(instance, inject(WowzaEndpointManager.class));
            } else if (field.getType().isAssignableFrom(Context.class)) {
                field.set(instance, new Context() {

                    @Override
                    public <T> T newInstance(Class<T> t) {
                        try {
                            return newClassInstance(framework, t, t);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
            } else if (field.getType().isAssignableFrom(AuthConfig.class)) {
                field.set(instance, newClassInstance(framework, Result.class, AuthConfig.class));
            } else if (field.getType().isAssignableFrom(EndpointState.class)) {
                field.set(instance, newClassInstance(framework, EndpointState.class, EndpointState.class));
            } else if (field.getType().isAssignableFrom(StreamingRequest.class)) {
                field.set(instance, inject(StreamingRequest.class));
            } else if (field.getType().isAssignableFrom(ScheduledExecutorService.class)) {
                field.set(instance, timer);
            } else if (field.getType().isAssignableFrom(RestClient.class)) {
                field.set(instance, newClassInstance(framework, RestClient.class, RestClient.class));
            } else if (field.getType().isAssignableFrom(URI.class)) {
                field.set(instance, inject(URI.class));
            }
        }
    }

    if (needsPostConstruct) {
        Method[] methods = tClass.equals(instance.getClass()) ? tClass.getMethods()
                : instance.getClass().getMethods();
        for (Method m : methods) {
            if (m.isAnnotationPresent(PostConstruct.class)) {
                try {
                    m.invoke(instance);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    return instance;
}

From source file:com.github.erchu.beancp.commons.NameBasedMapConvention.java

private List<BindingSide> getMatchingFieldByName(final Class sourceClass, final String atDestinationName,
        final MemberAccessType destinationMemberAccessType) {
    Optional<Field> exactMatchResult = Arrays.stream(sourceClass.getFields())
            .filter(i -> i.getName().equalsIgnoreCase(atDestinationName)).findFirst();

    if (exactMatchResult.isPresent()) {
        List<BindingSide> result = new LinkedList<>();
        result.add(new FieldBindingSide(exactMatchResult.get()));

        return result;
    }//ww  w. jav  a2  s  .  c  o  m

    if (_flateningEnabled) {
        Optional<Field> partiallyMatchResult = Arrays.stream(sourceClass.getFields())
                .filter(i -> StringUtils.startsWithIgnoreCase(atDestinationName, i.getName()))
                .sorted((x, y) -> y.getName().length() - x.getName().length()).findFirst();

        if (partiallyMatchResult.isPresent()) {
            BindingSide firstBinding = new FieldBindingSide(partiallyMatchResult.get());
            Class innerPropertyClass = firstBinding.getValueClass();

            return getInnerMatchingSourceMemberByName(innerPropertyClass, atDestinationName, firstBinding,
                    destinationMemberAccessType);
        } else {
            return null;
        }
    }

    return null;
}