Example usage for java.lang.reflect Field getModifiers

List of usage examples for java.lang.reflect Field getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Field getModifiers.

Prototype

public int getModifiers() 

Source Link

Document

Returns the Java language modifiers for the field represented by this Field object, as an integer.

Usage

From source file:cop.raml.mocks.MockUtils.java

private static TypeElementMock createClassElement(@NotNull Class<?> cls) throws ClassNotFoundException {
    TypeElementMock element = new TypeElementMock(cls.getName(), ElementKind.CLASS);
    element.setType(new TypeMirrorMock(element, TypeMirrorMock.getTypeKind(cls)));

    if (cls.getName().startsWith("cop.") || cls.getName().startsWith("spring.")) {
        VariableElementMock var;

        for (Field field : cls.getDeclaredFields())
            if ((var = createVariable(field.getName(), field.getType(),
                    Modifier.isStatic(field.getModifiers()))) != null)
                element.addEnclosedElement(setAnnotations(var, field));

        ExecutableElementMock exe;//from  w w  w  .  j ava2s  . co m

        for (Method method : cls.getDeclaredMethods())
            if ((exe = createExecutable(method)) != null)
                element.addEnclosedElement(setAnnotations(exe, method));
    }

    return setAnnotations(element, cls);
}

From source file:org.apache.kylin.rest.DebugTomcat.java

public static void setupDebugEnv() {
    try {//from   w  w w  . j  a  va 2s  .co  m
        System.setProperty("log4j.configuration", "file:../build/conf/kylin-tools-log4j.properties");

        // test_case_data/sandbox/ contains HDP 2.2 site xmls which is dev sandbox
        KylinConfig.setSandboxEnvIfPossible();
        overrideDevJobJarLocations();

        System.setProperty("spring.profiles.active", "testing");

        //avoid log permission issue
        if (System.getProperty("catalina.home") == null)
            System.setProperty("catalina.home", ".");

        if (StringUtils.isEmpty(System.getProperty("hdp.version"))) {
            System.err.println(
                    "No hdp.version set; Please set hdp.version in your jvm option, for example: -Dhdp.version=2.4.0.0-169");
            System.exit(1);
        }

        // workaround for job submission from win to linux -- https://issues.apache.org/jira/browse/MAPREDUCE-4052
        if (Shell.WINDOWS) {
            {
                Field field = Shell.class.getDeclaredField("WINDOWS");
                field.setAccessible(true);
                Field modifiersField = Field.class.getDeclaredField("modifiers");
                modifiersField.setAccessible(true);
                modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
                field.set(null, false);
            }
            {
                Field field = java.io.File.class.getDeclaredField("pathSeparator");
                field.setAccessible(true);
                Field modifiersField = Field.class.getDeclaredField("modifiers");
                modifiersField.setAccessible(true);
                modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
                field.set(null, ":");
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.apache.pulsar.common.configuration.PulsarConfigurationLoader.java

/**
 * Converts a PulsarConfiguration object to a ServiceConfiguration object.
 *
 * @param conf/*from   w w w  .  j  a  va2 s  . c o m*/
 * @param ignoreNonExistMember
 * @return
 * @throws IllegalArgumentException
 *             if conf has the field whose name is not contained in ServiceConfiguration and ignoreNonExistMember is false.
 * @throws RuntimeException
 */
public static ServiceConfiguration convertFrom(PulsarConfiguration conf, boolean ignoreNonExistMember)
        throws RuntimeException {
    try {
        final ServiceConfiguration convertedConf = ServiceConfiguration.class.newInstance();
        Field[] confFields = conf.getClass().getDeclaredFields();
        Arrays.stream(confFields).forEach(confField -> {
            try {
                Field convertedConfField = ServiceConfiguration.class.getDeclaredField(confField.getName());
                confField.setAccessible(true);
                if (!Modifier.isStatic(convertedConfField.getModifiers())) {
                    convertedConfField.setAccessible(true);
                    convertedConfField.set(convertedConf, confField.get(conf));
                }
            } catch (NoSuchFieldException e) {
                if (!ignoreNonExistMember) {
                    throw new IllegalArgumentException(
                            "Exception caused while converting configuration: " + e.getMessage());
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(
                        "Exception caused while converting configuration: " + e.getMessage());
            }
        });
        return convertedConf;
    } catch (InstantiationException e) {
        throw new RuntimeException("Exception caused while converting configuration: " + e.getMessage());
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Exception caused while converting configuration: " + e.getMessage());
    }
}

From source file:com.mh.commons.utils.Reflections.java

/**
 * ?? trim() /*from   ww  w . ja  v  a 2  s.  co m*/
 * ?? trim();  ??
 * @param obj
 * @param escapeList ??trim()
 * @return
 */
public static Object trim(Object obj, List<String> escapeList) {
    if (obj == null)
        return null;
    try {
        Field[] fields = obj.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                if (field.getModifiers() < 15 && field.getType().toString().equals("class java.lang.String")) {
                    Object val = FieldUtils.readField(field, obj, true);
                    if (val != null) {
                        if (escapeList != null && escapeList.indexOf(field.getName()) != -1)
                            continue;
                        FieldUtils.writeField(field, obj, val.toString().trim(), true);
                    }
                }
            }
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return obj;
}

From source file:com.antsdb.saltedfish.util.UberUtil.java

/**
 * warning, this method has no consideration of performance. it is written to help logging objects
 * //  w  w  w  .jav  a 2 s. c om
 * @param obj
 * @return
 */
public static String toString(Object obj) {
    if (obj == null) {
        return "NULL";
    }
    StringBuilder buf = new StringBuilder();
    for (Field i : obj.getClass().getFields()) {
        if ((i.getModifiers() & Modifier.STATIC) != 0) {
            continue;
        }
        buf.append(i.getName());
        buf.append(":");
        Object value;
        try {
            value = i.get(obj);
        } catch (Exception x) {
            value = x.getMessage();
        }
        if (value != null) {
            buf.append(value.toString());
        } else {
            buf.append("NULL");
        }
        buf.append('\n');
    }
    return buf.toString();
}

From source file:edu.brown.utils.ClassUtil.java

/**
 * @param clazz//from w  w  w  . j  a v a2 s  .co  m
 * @return
 */
public static <T> Field[] getFieldsByType(Class<?> clazz, Class<? extends T> fieldType) {
    List<Field> fields = new ArrayList<Field>();
    for (Field f : clazz.getDeclaredFields()) {
        int modifiers = f.getModifiers();
        if (Modifier.isTransient(modifiers) == false && Modifier.isPublic(modifiers) == true
                && Modifier.isStatic(modifiers) == false
                && ClassUtil.getSuperClasses(f.getType()).contains(fieldType)) {

            fields.add(f);
        }
    } // FOR
    return (fields.toArray(new Field[fields.size()]));
}

From source file:io.github.eternalbits.compactvd.CompactVD.java

private static void dump(Object obj, String in) {
    for (Field fld : obj.getClass().getDeclaredFields()) {
        try {/* ww  w  .ja  v a  2s  . c  o m*/
            if (!Modifier.isPrivate(fld.getModifiers())) {
                if (fld.getAnnotation(Deprecated.class) == null) {
                    if (!fld.getType().isAssignableFrom(List.class)) {
                        System.out.println(in + fld.getName() + ": " + fld.get(obj));
                    } else {
                        int i = 0;
                        for (Object item : (List<?>) fld.get(obj)) {
                            System.out.println(in + fld.getName() + "[" + i + "]");
                            dump(item, in + "    ");
                            i++;
                        }
                    }
                }
            }
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.yiji.openapi.sdk.util.Reflections.java

public static Set<String> getFieldNames(Class<?> pojoClass) {
    Set<String> propertyNames = new HashSet<String>();
    Class<?> clazz = pojoClass;
    do {//w w w.  j  a v a 2s.  c om
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isStatic(field.getModifiers())) {
                propertyNames.add(field.getName());

            }
        }
        clazz = clazz.getSuperclass();
    } while (clazz != null && !clazz.getSimpleName().equalsIgnoreCase("Object"));
    return propertyNames;
}

From source file:org.apache.hadoop.hbase.util.ClassSize.java

/**
 * The estimate of the size of a class instance depends on whether the JVM
 * uses 32 or 64 bit addresses, that is it depends on the size of an object
 * reference. It is a linear function of the size of a reference, e.g.
 * 24 + 5*r where r is the size of a reference (usually 4 or 8 bytes).
 *
 * This method returns the coefficients of the linear function, e.g. {24, 5}
 * in the above example./*from ww  w. j  a  va  2  s. c  om*/
 *
 * @param cl A class whose instance size is to be estimated
 * @param debug debug flag
 * @return an array of 3 integers. The first integer is the size of the
 * primitives, the second the number of arrays and the third the number of
 * references.
 */
@SuppressWarnings("unchecked")
private static int[] getSizeCoefficients(Class cl, boolean debug) {
    int primitives = 0;
    int arrays = 0;
    //The number of references that a new object takes
    int references = nrOfRefsPerObj;
    int index = 0;

    for (; null != cl; cl = cl.getSuperclass()) {
        Field[] field = cl.getDeclaredFields();
        if (null != field) {
            for (Field aField : field) {
                if (Modifier.isStatic(aField.getModifiers()))
                    continue;
                Class fieldClass = aField.getType();
                if (fieldClass.isArray()) {
                    arrays++;
                    references++;
                } else if (!fieldClass.isPrimitive()) {
                    references++;
                } else {// Is simple primitive
                    String name = fieldClass.getName();

                    if (name.equals("int") || name.equals("I"))
                        primitives += Bytes.SIZEOF_INT;
                    else if (name.equals("long") || name.equals("J"))
                        primitives += Bytes.SIZEOF_LONG;
                    else if (name.equals("boolean") || name.equals("Z"))
                        primitives += Bytes.SIZEOF_BOOLEAN;
                    else if (name.equals("short") || name.equals("S"))
                        primitives += Bytes.SIZEOF_SHORT;
                    else if (name.equals("byte") || name.equals("B"))
                        primitives += Bytes.SIZEOF_BYTE;
                    else if (name.equals("char") || name.equals("C"))
                        primitives += Bytes.SIZEOF_CHAR;
                    else if (name.equals("float") || name.equals("F"))
                        primitives += Bytes.SIZEOF_FLOAT;
                    else if (name.equals("double") || name.equals("D"))
                        primitives += Bytes.SIZEOF_DOUBLE;
                }
                if (debug) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("" + index + " " + aField.getName() + " " + aField.getType());
                    }
                }
                index++;
            }
        }
    }
    return new int[] { primitives, arrays, references };
}

From source file:com.xutils.view.ViewInjectorImpl.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, Class<?> handlerType, ViewFinder finder) {

    if (handlerType == null || IGNORED.contains(handlerType)) {
        return;/*from  w  w w.ja va 2  s  . c om*/
    }

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {

            Class<?> fieldType = field.getType();
            if (
            /* ??? */ Modifier.isStatic(field.getModifiers()) ||
            /* ?final */ Modifier.isFinal(field.getModifiers()) ||
            /* ? */ fieldType.isPrimitive() ||
            /* ? */ fieldType.isArray()) {
                continue;
            }

            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.value(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    } else {
                        throw new RuntimeException("Invalid id(" + viewInject.value() + ") for @ViewInject!"
                                + handlerType.getSimpleName());
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    }

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {

            if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPrivate(method.getModifiers())) {
                continue;
            }

            //??event
            Event event = method.getAnnotation(Event.class);
            if (event != null) {
                try {
                    // id?
                    int[] values = event.value();
                    int[] parentIds = event.parentId();
                    int parentIdsLen = parentIds == null ? 0 : parentIds.length;
                    //id?ViewInfo???
                    for (int i = 0; i < values.length; i++) {
                        int value = values[i];
                        if (value > 0) {
                            ViewInfo info = new ViewInfo();
                            info.value = value;
                            info.parentId = parentIdsLen > i ? parentIds[i] : 0;
                            method.setAccessible(true);
                            EventListenerManager.addEventMethod(finder, info, event, handler, method);
                        }
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    }

    injectObject(handler, handlerType.getSuperclass(), finder);
}