Example usage for java.lang.reflect Modifier isStatic

List of usage examples for java.lang.reflect Modifier isStatic

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isStatic.

Prototype

public static boolean isStatic(int mod) 

Source Link

Document

Return true if the integer argument includes the static modifier, false otherwise.

Usage

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

private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException,
        InstantiationException, InvocationTargetException, NoSuchMethodException {
    if (nmsChatSerializerGsonInstance == null) {
        // Find the field and its value, completely bypassing obfuscation
        for (Field declaredField : Reflection.getNMSClass("ChatSerializer").getDeclaredFields()) {
            if (Modifier.isFinal(declaredField.getModifiers())
                    && Modifier.isStatic(declaredField.getModifiers())
                    && declaredField.getType().getName().endsWith("Gson")) {
                // We've found our field
                declaredField.setAccessible(true);
                nmsChatSerializerGsonInstance = declaredField.get(null);
                fromJsonMethod = nmsChatSerializerGsonInstance.getClass().getMethod("fromJson", String.class,
                        Class.class);
                break;
            }/*from   w w w .j  av  a 2  s  .  c  o  m*/
        }
    }

    // Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)' than to reflectively call it
    // Of course, the implementation may change, but fuzzy matches might break with signature changes
    Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json,
            Reflection.getNMSClass("IChatBaseComponent"));

    return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

private void exportData(String dataSource, HttpServletResponse response) throws Exception {
    ServiceDescription serviceDesc = findService(dataSource);
    List<? extends Object> serviceResult = null;
    if (serviceDesc.getFindAll() != null) {
        Class<?>[] parameterTypes = serviceDesc.getFindAll().getParameterTypes();
        Object[] realParameters = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            if (parameterTypes[i].equals(ServiceContext.class)) {
                realParameters[i] = ServiceContextStore.get();
            } else if (parameterTypes[i].equals(PagingParameter.class)) {
                realParameters[i] = PagingParameter.rowAccess(0, 1000);
            } else {
                throw new IllegalArgumentException("findAll parameter #" + i + " for '" + dataSource
                        + "' has unknown type '" + parameterTypes[i].getName() + "'");
            }//w ww. j a va 2 s .com
        }
        if (serviceDesc.getFindAll().getReturnType().equals(PagedResult.class)) {
            PagedResult pagedServiceResult = (PagedResult) serviceDesc.getFindAll()
                    .invoke(serviceDesc.getInstance(), realParameters);
            serviceResult = pagedServiceResult.getValues();
        } else {
            serviceResult = (List<? extends Object>) serviceDesc.getFindAll().invoke(serviceDesc.getInstance(),
                    realParameters);
        }
    } else {
        throw new IllegalArgumentException("No fetch (findAll) operation available");
    }

    // application/vnd.oasis.opendocument.spreadsheet
    // application/vnd.ms-excel
    response.setContentType("application/vnd.oasis.opendocument.spreadsheet;charset=UTF-8");
    response.setHeader("Content-Disposition", "filename=" + dataSource + ".csv");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "-1");

    boolean first = true;
    List<Method> methods = new ArrayList<Method>();
    for (Object dataRow : serviceResult) {
        // prepare header
        if (first) {
            first = false;
            StringBuilder header = new StringBuilder();

            // Resolve getId method
            Method idMethod;
            try {
                idMethod = dataRow.getClass().getMethod("getId", (Class<?>[]) null);
            } catch (Throwable th) {
                idMethod = null;
            }
            if (idMethod != null) {
                methods.add(idMethod);
                header.append("Id " + READ_ONLY + ",");
            }

            // Iterate through methods
            for (Class curClass = dataRow.getClass(); curClass != Object.class; curClass = curClass
                    .getSuperclass()) {
                Method[] declaredMethods = curClass.getDeclaredMethods();
                for (Method m : declaredMethods) {
                    if (m.getName().startsWith(GET_PREFIX) && Modifier.isPublic(m.getModifiers())
                            && !Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0
                            && !"getKey".equals(m.getName()) && !"getCreatedDate".equals(m.getName())
                            && !"getCreatedBy".equals(m.getName()) && !"getLastUpdated".equals(m.getName())
                            && !"getLastUpdatedBy".equals(m.getName()) && !"getVersion".equals(m.getName())
                            && !"getUuid".equals(m.getName()) && !"getId".equals(m.getName())) {
                        Method setMethod;
                        try {
                            setMethod = curClass.getMethod(
                                    SET_PREFIX + m.getName().substring(GET_PREFIX.length()),
                                    new Class[] { m.getReturnType() });
                        } catch (Throwable ex) {
                            setMethod = null;
                        }
                        String readOnly = "";
                        if (setMethod == null) {
                            readOnly = READ_ONLY;
                        }
                        header.append(m.getName().substring(GET_PREFIX.length())).append(readOnly).append(",");
                        methods.add(m);
                    }
                }
            }
            response.getWriter().println(header.length() > 0 ? header.substring(0, header.length() - 1) : "");
        }

        // Export data
        StringBuilder csvRow = new StringBuilder();
        for (Method m : methods) {
            Object value = m.invoke(dataRow, (Object[]) null);
            if (value == null) {
                csvRow.append("null,");
            } else if (value instanceof Map) {
                csvRow.append("HUH-MAPA");
                csvRow.append(",");
            } else if (value instanceof Collection) {
                csvRow.append("HUH-COLLECTION");
                csvRow.append(",");
            } else if (value instanceof List) {
                csvRow.append("HUH-LIST");
                csvRow.append(",");
            } else if (value instanceof Object[]) {
                csvRow.append("HUH-ARRAY");
                csvRow.append(",");
            } else if (value instanceof Date) {
                csvRow.append(dateFormat.format((Date) value));
                csvRow.append(",");
            } else if (value instanceof Boolean) {
                csvRow.append(((Boolean) value) ? "TRUE" : "FALSE");
                csvRow.append(",");
            } else if (value instanceof Number) {
                csvRow.append(value);
                csvRow.append(",");
            } else if (value instanceof CharSequence) {
                csvRow.append(Q).append(((CharSequence) value).toString().replaceAll(Q, Q + Q)).append(Q);
                csvRow.append(",");
            } else if (value instanceof Enum) {
                String enumName = ((Enum) value).name();
                csvRow.append(Q + enumName + Q);
                csvRow.append(",");
            } else {
                csvRow.append("SOMETHING ELSE " + value.getClass());
                csvRow.append(",");
            }
        }
        response.getWriter().println(csvRow.length() > 0 ? csvRow.substring(0, csvRow.length() - 1) : "");
    }
    return;
}

From source file:org.apache.openjpa.meta.FieldMetaData.java

/**
 * Convert the given field value to its external value through the
 * provided externalizer, or return the value as-is if no externalizer.
 */// w w  w.ja  v  a2s.  c  om
public Object getExternalValue(Object val, StoreContext ctx) {
    Map extValues = getExternalValueMap();
    if (extValues != null) {
        Object foundVal = extValues.get(val);
        if (foundVal == null) {
            throw new UserException(
                    _loc.get("bad-externalized-value", new Object[] { val, extValues.keySet(), this }))
                            .setFatal(true).setFailedObject(val);
        } else {
            return foundVal;
        }
    }

    Method externalizer = getExternalizerMethod();
    if (externalizer == null)
        return val;

    // special case for queries: allow the given value to pass through
    // as-is if it is already in externalized form
    if (val != null && getType().isInstance(val)
            && (!getDeclaredType().isInstance(val) || getDeclaredType() == Object.class))
        return val;

    try {
        // either invoke the static toExternal(val[, ctx]) method, or the
        // non-static val.toExternal([ctx]) method
        if (Modifier.isStatic(externalizer.getModifiers())) {
            if (externalizer.getParameterTypes().length == 1)
                return externalizer.invoke(null, new Object[] { val });
            return externalizer.invoke(null, new Object[] { val, ctx });
        }
        if (val == null)
            return null;
        if (externalizer.getParameterTypes().length == 0)
            return externalizer.invoke(val, (Object[]) null);
        return externalizer.invoke(val, new Object[] { ctx });
    } catch (OpenJPAException ke) {
        throw ke;
    } catch (Exception e) {
        throw new MetaDataException(_loc.get("externalizer-err", this, Exceptions.toString(val), e.toString()))
                .setCause(e);
    }
}

From source file:com.taobao.adfs.util.Utilities.java

/**
 * not support more override method, ASM is a better solution.
 * refer: http://stackoverflow.com/questions/4024587/get-callers-method-not-name
 *///from   w w w. j a  va 2s  .  c  o  m
public static Method getCaller(boolean staticMethod) throws IOException {
    StackTraceElement caller = Thread.currentThread().getStackTrace()[3];
    Class<?> clazz = ClassCache.getWithIOException(caller.getClassName());
    for (Method method : clazz.getDeclaredMethods()) {
        if (!method.getName().equals(caller.getMethodName()))
            continue;
        if (Modifier.isStatic(method.getModifiers()) != staticMethod)
            continue;
        return method;
    }
    throw new IOException("fail to get caller");
}

From source file:Base64.java

/**
 * Draws a line on the screen at the specified index. Default is green.
 * <p/>/*from   w  w  w .  j a va  2 s. co m*/
 * Available colours: red, green, cyan, purple, white.
 *
 * @param render The Graphics object to be used.
 * @param row    The index where you want the text.
 * @param text   The text you want to render. Colours can be set like [red].
 */
public static void drawLine(Graphics render, int row, String text) {
    FontMetrics metrics = render.getFontMetrics();
    int height = metrics.getHeight() + 4; // height + gap
    int y = row * height + 15 + 19;
    String[] texts = text.split("\\[");
    int xIdx = 7;
    Color cur = Color.GREEN;
    for (String t : texts) {
        for (@SuppressWarnings("unused")
        String element : COLOURS_STR) {
            // String element = COLOURS_STR[i];
            // Don't search for a starting '[' cause it they don't exists.
            // we split on that.
            int endIdx = t.indexOf(']');
            if (endIdx != -1) {
                String colorName = t.substring(0, endIdx);
                if (COLOR_MAP.containsKey(colorName)) {
                    cur = COLOR_MAP.get(colorName);
                } else {
                    try {
                        Field f = Color.class.getField(colorName);
                        int mods = f.getModifiers();
                        if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
                            cur = (Color) f.get(null);
                            COLOR_MAP.put(colorName, cur);
                        }
                    } catch (Exception ignored) {
                    }
                }
                t = t.replace(colorName + "]", "");
            }
        }
        render.setColor(Color.BLACK);
        render.drawString(t, xIdx, y + 1);
        render.setColor(cur);
        render.drawString(t, xIdx, y);
        xIdx += metrics.stringWidth(t);
    }
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Copy bean properties.  Called with the copy object on the stack.  Must
 * return with the copy object on the stack.
 *//*from w  w w.j  a  v a  2 s  .c  om*/
private void copyProperties(Class type, Code code) {
    int copy = code.getNextLocalsIndex();
    code.astore().setLocal(copy);

    Method[] meths = type.getMethods();
    Method getter;
    int mods;
    for (int i = 0; i < meths.length; i++) {
        mods = meths[i].getModifiers();
        if (!Modifier.isPublic(mods) || Modifier.isStatic(mods))
            continue;
        if (!startsWith(meths[i].getName(), "set") || meths[i].getParameterTypes().length != 1)
            continue;
        getter = findGetter(type, meths[i]);
        if (getter == null)
            continue;

        // copy.setXXX(orig.getXXX());
        code.aload().setLocal(copy);
        code.aload().setParam(0);
        code.checkcast().setType(type);
        code.invokevirtual().setMethod(getter);
        code.invokevirtual().setMethod(meths[i]);
    }
    code.aload().setLocal(copy);
}

From source file:fr.certu.chouette.command.Command.java

/**
 * @param object//www  .jav a  2 s  .c  o  m
 * @throws Exception
 */
private void printFields(Object object, String indent) throws Exception {
    try {
        Class<?> c = object.getClass();
        Field[] fields = c.getSuperclass().getDeclaredFields();
        for (Field field : fields) {
            int m = field.getModifiers();
            if (Modifier.isPrivate(m) && !Modifier.isStatic(m)) {
                printField(c, field, indent);
            }

        }

        fields = c.getDeclaredFields();
        for (Field field : fields) {
            int m = field.getModifiers();
            if (Modifier.isPrivate(m) && !Modifier.isStatic(m)) {
                printField(c, field, indent);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:ca.oson.json.Oson.java

private boolean ignoreModifiers(int modifiers, Set<MODIFIER> includeFieldsWithModifiers) {
    //Set<MODIFIER> includeFieldsWithModifiers = getIncludeFieldsWithModifiers();
    if (includeFieldsWithModifiers == null || includeFieldsWithModifiers.size() == 0) {
        // by default, transient and volatile are ignored
        // unless you specify otherwise, by using MODIFIER.Transient enum, or all
        if (Modifier.isTransient(modifiers)) {
            return true;
        }/*from  w w  w  . j  a  v  a2 s. c  o  m*/
        if (Modifier.isVolatile(modifiers)) {
            return true;
        }

        return false;
    }

    if (includeFieldsWithModifiers.contains(MODIFIER.All)) {
        return false;
    }

    for (MODIFIER modifier : includeFieldsWithModifiers) {
        switch (modifier) {
        case Abstract:
            if (Modifier.isAbstract(modifiers)) {
                return false;
            }
            break;
        case Final:
            if (Modifier.isFinal(modifiers)) {
                return false;
            }
            break;
        case Interface:
            if (Modifier.isInterface(modifiers)) {
                return false;
            }
            break;
        case Native:
            if (Modifier.isNative(modifiers)) {
                return false;
            }
            break;
        case Private:
            if (Modifier.isPrivate(modifiers)) {
                return false;
            }
            break;
        case Protected:
            if (Modifier.isProtected(modifiers)) {
                return false;
            }
            break;
        case Public:
            if (Modifier.isPublic(modifiers)) {
                return false;
            }
            break;
        case Package:
            if (ObjectUtil.isPackage(modifiers)) {
                return false;
            }
            break;
        case Static:
            if (Modifier.isStatic(modifiers)) {
                return false;
            }
            break;
        case Strict:
            if (Modifier.isStrict(modifiers)) {
                return false;
            }
            break;
        case Synchronized:
            if (Modifier.isSynchronized(modifiers)) {
                return false;
            }
            break;
        case Transient:
            if (Modifier.isTransient(modifiers)) {
                return false;
            }
            break;
        case Volatile:
            if (Modifier.isVolatile(modifiers)) {
                return false;
            }
            break;
        }
    }

    return true;
}

From source file:com.judoscript.jamaica.JavaClassCreator.java

public final String macroGetField(String name) throws JavaClassCreatorException {
    boolean isStatic = isStaticField(name);
    if (!isStatic && Modifier.isStatic(getMethodAccessFlags()))
        throw new JavaClassCreatorException("Instance data member " + name
                + " can not be accessed from static method " + getMethodName() + "().");
    if (!isStatic)
        inst_aload_0();//from   ww  w  .j av a2  s .co  m
    String type = getFieldType(name);
    instGetPut(isStatic ? 178 : 180, getClassName(), name, type);
    return type;
}

From source file:fr.certu.chouette.command.Command.java

/**
 * @param itemType/*from ww w . ja va2 s  . com*/
 * @param indent
 * @throws Exception
 */
private void printFieldDetails(Class<?> itemType, String indent) throws Exception {
    String itemName = itemType.getName();
    if (itemName.startsWith("fr.certu.chouette.model.neptune.type.")) {
        if (itemName.endsWith("Enum")) {
            Field[] fields = itemType.getDeclaredFields();
            System.out.print(indent + "     ");

            String text = "";
            for (Field field : fields) {
                int m = field.getModifiers();
                if (Modifier.isPublic(m) && Modifier.isStatic(m) && Modifier.isFinal(m)) {
                    Object instance = field.get(null);
                    String name = instance.toString();
                    if (text.length() + name.length() > 79) {
                        System.out.print(text + "\n" + indent + "     ");
                        text = "";
                    }
                    text += name + " ";
                }
            }
            System.out.println(text);
        } else {
            Object instance = itemType.newInstance();
            printFields(instance, indent + "     ");
        }
    } else if (itemName.startsWith("fr.certu.chouette.model.neptune.")) {
        Object instance = itemType.newInstance();
        if (instance instanceof NeptuneIdentifiedObject) {
            String simpleName = itemType.getSimpleName();
            if (simpleName.equals("AreaCentroid")) {
                printFields(instance, indent + "     ");
            }
        } else {
            printFields(instance, indent + "     ");
        }

    }
}