Example usage for java.lang Class getField

List of usage examples for java.lang Class getField

Introduction

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

Prototype

@CallerSensitive
public Field getField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

Usage

From source file:org.red5.server.util.ScopeUtils.java

public static Object getScopeService(IScope scope, Class<?> intf, Class<?> defaultClass, boolean checkHandler) {
    if (scope == null || intf == null) {
        return null;
    }/*from ww w  .j a v a 2 s.  c  o  m*/
    // We expect an interface
    assert intf.isInterface();

    String attr = IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName();
    if (scope.hasAttribute(attr)) {
        // return cached service
        return scope.getAttribute(attr);
    }

    Object handler = null;
    if (checkHandler) {
        IScope current = scope;
        while (current != null) {
            IScopeHandler scopeHandler = current.getHandler();
            if (intf.isInstance(scopeHandler)) {
                handler = scopeHandler;
                break;
            }
            if (!current.hasParent()) {
                break;
            }
            current = current.getParent();
        }
    }

    if (handler == null && IScopeService.class.isAssignableFrom(intf)) {
        // we've got an IScopeService, try to lookup bean
        Field key = null;
        Object serviceName = null;
        try {
            key = intf.getField("BEAN_NAME");
            serviceName = key.get(null);
            if (serviceName instanceof String) {
                handler = getScopeService(scope, (String) serviceName, defaultClass);
            }
        } catch (Exception e) {
            log.debug("No string field 'BEAN_NAME' in that interface");
        }
    }
    if (handler == null && defaultClass != null) {
        try {
            handler = defaultClass.newInstance();
        } catch (Exception e) {
            log.error("", e);
        }
    }
    // cache service
    scope.setAttribute(attr, handler);
    return handler;
}

From source file:org.ambient.control.config.EditConfigFragment.java

private void integrateConfiguration(Object configuration) {
    try {/*from  w  w  w. j a  v  a 2  s.  c o m*/
        Class<? extends Object> myConfigurationClass = beanToEdit.getClass();
        Field myField = myConfigurationClass.getField(whereToMergeChildBean.fieldName);

        if (whereToMergeChildBean.type.equals(WhereToPutType.FIELD)) {
            myField.set(beanToEdit, configuration);

        } else if (whereToMergeChildBean.type.equals(WhereToPutType.LIST)) {
            @SuppressWarnings("unchecked")
            // checked in line above
            List<Object> list = (List<Object>) myField.get(beanToEdit);
            if (whereToMergeChildBean.positionInList != null) {
                list.set(whereToMergeChildBean.positionInList, configuration);
            } else {
                list.add(configuration);
            }

        } else if (whereToMergeChildBean.type.equals(WhereToPutType.MAP)) {
            @SuppressWarnings("unchecked")
            // checked one line above
            Map<Object, Object> map = (Map<Object, Object>) myField.get(beanToEdit);
            map.put(whereToMergeChildBean.keyInMap, configuration);
        }

    } catch (Exception e) {
        Log.e(LOG, "error trying to integrate data from child into configuration", e);
    }

    // we do not want to be called again
    this.valueToIntegrate = null;
}

From source file:com.autentia.intra.dao.hibernate.HibernateManagerBase.java

/**
 * Inserta un objeto de negocio en base de datos
 *
 * @param obj a insertar//from  www. j a va  2  s  . com
 */
public void insert(ITransferObject obj) throws DataAccException {
    log.debug("insert");
    Session session = null;
    try {

        session = HibernateUtil.currentSession();
        session.beginTransaction();
        obj.setOwnerId(SpringUtils.getPrincipal().getId());
        obj.setDepartmentId(SpringUtils.getPrincipal().getDepartmentId());
        Date d = new Date();
        obj.setInsertDate(d);
        obj.setUpdateDate(d);
        session.save(obj);
        Class cls = obj.getClass();
        try {
            if ((Boolean) cls.getField("historial").get(null)) {
                Historial entrada = new Historial();
                entrada.setFechaHora(new Date());
                entrada.setUsuario(SpringUtils.getPrincipal().getUser());
                entrada.setKlazz(cls);
                entrada.setIdObjeto(obj.getId());
                entrada.setTipoCambio(HistorialType.CREADO);
                session.save(entrada);
            }
        } catch (NoSuchFieldException ex) {
            //pass
        }
        session.getTransaction().commit();
        log.debug("objeto correctamente insertado");
        if (this.cacheable)
            HibernateManagerBase.removeCacheFor(obj.getClass().getName());
    } catch (Exception ex) {
        log.error("insert - exception", ex);
        StringBuffer msg = new StringBuffer("Error insertando el objeto: ");
        msg.append(obj);
        /*
        if(session!=null) {
           session.flush();
           session.close();
        }
        */
        throw new DataAccException(msg.toString(), ex);
    }
    /*finally{
        HibernateUtil.closeSession(session);
    }*/
}

From source file:com.autentia.intra.dao.hibernate.HibernateManagerBase.java

/**
 * Actualiza una objeto de negocio en base de datos
 *
 * @param obj el objeto de negocio a actualizar
 *///from  w w  w .  ja  v  a2 s  .  c o m
public void update(ITransferObject obj, Serializable pk) throws DataAccException {
    log.debug("update");
    Session session = null;
    try {

        session = HibernateUtil.currentSession();
        session.beginTransaction();
        // Cargamos el objeto antiguo
        //IZA         Object objOld = session.load(obj.getClass(), pk);
        log.debug("objeto con clave '" + pk + "' recuperado");
        // Copiamos las propiedades del objeto nuevo al antiguo
        //IZA         BeanUtils.copyProperties(objOld,obj);
        // Actualizamos
        //IZA         session.update(objOld);
        obj.setUpdatedById(SpringUtils.getPrincipal().getId());
        obj.setUpdateDate(new Date());
        //obj = obj.getClass().cast(session.merge(obj));
        try {
            session.update(obj);
        } catch (NonUniqueObjectException ex) {
            session.clear();
            session.update(obj);
        }
        Class cls = obj.getClass();
        try {
            if ((Boolean) cls.getField("historial").get(null)) {
                Historial entrada = new Historial();
                entrada.setFechaHora(new Date());
                entrada.setUsuario(SpringUtils.getPrincipal().getUser());
                entrada.setKlazz(cls);
                entrada.setIdObjeto(obj.getId());
                entrada.setTipoCambio(HistorialType.MODIFICADO);
                session.save(entrada);
            }
        } catch (NoSuchFieldException ex) {
            //pass
        }
        try {
            session.getTransaction().commit();

            log.debug("objeto con clave '" + pk + "' correctamente actualizado");
            if (this.cacheable)
                HibernateManagerBase.removeCacheFor(obj.getClass().getName());
        } catch (HibernateException ex) {
            session.getTransaction().rollback();
            session.clear();
        }
    } catch (Exception ex) {
        String msg = "Error actualizando el objeto '" + obj + "' con clave primaria '" + pk + "'";
        log.debug("error actualizando el objeto '" + pk + "': " + msg);
        throw new DataAccException(msg, ex);
    }
    /*finally{
        HibernateUtil.closeSession(session);
    }*/
}

From source file:optional.BasicFilter.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;

    filterConfig.getServletContext();//from w  ww .  j  av  a2  s  .c  o m

    String packagepath = filterConfig.getInitParameter("");
    packagepath = "";

    // configs

    // actions

    String path = filterConfig.getServletContext().getRealPath("/WEB-INF/classes" + packagepath);

    // Klassen finden
    ArrayList list = ActionPlugin.getClasses(path, packagepath);

    System.out.println("## looking for direct actions ##");
    for (Iterator iterator = list.iterator(); iterator.hasNext();) {
        try {
            Class clazz = Class.forName((String) iterator.next());

            if (!isInterfaceImplementer(clazz, DirectInterface.class)) {
                continue;
            }

            // store Actionclass and its configuration
            ConfigWrapper wrapper = new ConfigWrapper();

            wrapper.setConfig((ActionConfig) clazz.getField("struts").get(clazz));
            wrapper.setActionclass(clazz);

            wrapper.getConfig().setPath(getPathFromClassName(clazz.getName(), "Action"));

            System.out.println(wrapper.getConfig().getPath() + "\n" + clazz);

            actions.put(wrapper.getConfig().getPath(), wrapper);

        } catch (Exception e) {
            continue;
        }
    }
    System.out.println("## looking for direct actions DONE ##");

    //      request.setCharacterEncoding(encoding);  // CharsetFilter
    //      response.setCharacterEncoding(encoding);
}

From source file:com.dtr.zxing.activity.CaptureActivity.java

private int getStatusBarHeight() {
    try {//  w ww .ja va2 s  .  c  o  m
        Class<?> c = Class.forName("com.android.internal.R$dimen");
        Object obj = c.newInstance();
        Field field = c.getField("status_bar_height");
        int x = Integer.parseInt(field.get(obj).toString());
        return getResources().getDimensionPixelSize(x);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}

From source file:com.sun.socialsite.util.DebugBeanJsonConverter.java

private Object convertEnum(Class<?> enumKeyType, JSONObject jsonEnum)
        throws JSONException, IllegalAccessException, NoSuchFieldException {
    // TODO This isnt injector friendly but perhaps implementors dont need it. If they do a
    // refactoring of the Enum handling in general is needed.
    Object value;/*from   ww w  .  jav a  2 s .  co  m*/
    if (jsonEnum.has(Enum.Field.VALUE.toString())) {
        Enum.EnumKey enumKey = (Enum.EnumKey) enumKeyType
                .getField(jsonEnum.getString(Enum.Field.VALUE.toString())).get(null);
        String displayValue = null;
        if (jsonEnum.has(Enum.Field.DISPLAY_VALUE.toString())) {
            displayValue = jsonEnum.getString(Enum.Field.DISPLAY_VALUE.toString());
        }
        value = new EnumImpl<Enum.EnumKey>(enumKey, displayValue);
    } else {
        value = new EnumImpl<Enum.EnumKey>(null, jsonEnum.getString(Enum.Field.DISPLAY_VALUE.toString()));
    }
    return value;
}

From source file:ubic.gemma.web.taglib.ConstantsTei.java

/**
 * Return information about the scripting variables to be created.
 *///from w  ww .jav  a  2 s .  com
@Override
public VariableInfo[] getVariableInfo(TagData data) {
    // loop through and expose all attributes
    List<VariableInfo> vars = new ArrayList<VariableInfo>();

    try {
        String clazz = data.getAttributeString("className");

        if (clazz == null) {
            clazz = Constants.class.getName();
        }

        Class<?> c = Class.forName(clazz);

        // if no var specified, get all
        if (data.getAttributeString("var") == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (int i = 0; i < fields.length; i++) {
                vars.add(new VariableInfo(fields[i].getName(), "java.lang.String", true, VariableInfo.AT_END));
            }
        } else {
            String var = data.getAttributeString("var");
            vars.add(
                    new VariableInfo(c.getField(var).getName(), "java.lang.String", true, VariableInfo.AT_END));
        }
    } catch (Exception cnf) {
        log.error(cnf.getMessage());
        cnf.printStackTrace();
    }

    return vars.toArray(new VariableInfo[] {});
}

From source file:com.snipme.record.Record.java

/**
 * Creates a JSONObject that represents a File from the Uri
 *
 * @param data the Uri of the audio/image/video
 * @return a JSONObject that represents a File
 * @throws IOException//w ww  .ja  va2  s .c o  m
 */
private JSONObject createMediaFile(Uri data) {
    File fp = webView.getResourceApi().mapUriToFile(data);
    JSONObject obj = new JSONObject();

    Class webViewClass = webView.getClass();
    PluginManager pm = null;
    try {
        Method gpm = webViewClass.getMethod("getPluginManager");
        pm = (PluginManager) gpm.invoke(webView);
    } catch (NoSuchMethodException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    }
    if (pm == null) {
        try {
            Field pmf = webViewClass.getField("pluginManager");
            pm = (PluginManager) pmf.get(webView);
        } catch (NoSuchFieldException e) {
        } catch (IllegalAccessException e) {
        }
    }
    FileUtils filePlugin = (FileUtils) pm.getPlugin("File");
    LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(fp.getAbsolutePath());

    try {
        // File properties
        obj.put("name", fp.getName());
        obj.put("fullPath", fp.toURI().toString());
        if (url != null) {
            obj.put("localURL", url.toString());
        }
        // Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files
        // are reported as video/3gpp. I'm doing this hacky check of the URI to see if it
        // is stored in the audio or video content store.
        if (fp.getAbsoluteFile().toString().endsWith(".3gp")
                || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
            if (data.toString().contains("/audio/")) {
                obj.put("type", AUDIO_3GPP);
            } else {
                obj.put("type", VIDEO_3GPP);
            }
        } else {
            obj.put("type", FileHelper.getMimeType(Uri.fromFile(fp), cordova));
        }

        obj.put("lastModifiedDate", fp.lastModified());
        obj.put("size", fp.length());
    } catch (JSONException e) {
        // this will never happen
        e.printStackTrace();
    }
    return obj;
}

From source file:com.jxva.exception.ExceptionUtil.java

/**
 * <p>Checks whether this <code>Throwable</code> class can store a cause.</p>
 *
 * <p>This method does <b>not</b> check whether it actually does store a cause.<p>
 *
 * @param throwable  the <code>Throwable</code> to examine, may be null
 * @return boolean <code>true</code> if nested otherwise <code>false</code>
 * @since 2.0//  w  w w  . j  a  v a2s  .c  om
 */
public static boolean isNestedThrowable(Throwable throwable) {
    if (throwable == null) {
        return false;
    }

    if (throwable instanceof Nestable) {
        return true;
    } else if (throwable instanceof SQLException) {
        return true;
    } else if (throwable instanceof InvocationTargetException) {
        return true;
    } else if (isThrowableNested()) {
        return true;
    }

    Class<? extends Throwable> cls = throwable.getClass();
    synchronized (CAUSE_METHOD_NAMES) {
        for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
            try {
                Method method = cls.getMethod(CAUSE_METHOD_NAMES[i]);
                if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
                    return true;
                }
            } catch (NoSuchMethodException ignored) {
                // exception ignored
            } catch (SecurityException ignored) {
                // exception ignored
            }
        }
    }

    try {
        Field field = cls.getField("detail");
        if (field != null) {
            return true;
        }
    } catch (NoSuchFieldException ignored) {
        // exception ignored
    } catch (SecurityException ignored) {
        // exception ignored
    }

    return false;
}