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:ClassVersionInfo.java

public ClassVersionInfo(String name, ClassLoader loader) throws ClassNotFoundException {
    this.name = name;
    Class c = loader.loadClass(name);
    CodeSource cs = c.getProtectionDomain().getCodeSource();
    if (cs != null)
        location = cs.getLocation();/*from w w  w.ja  v  a2  s. c om*/
    if (c.isInterface() == false) {
        ObjectStreamClass osc = ObjectStreamClass.lookup(c);
        if (osc != null) {
            serialVersion = osc.getSerialVersionUID();
            try {
                c.getDeclaredField("serialVersionUID");
                hasExplicitSerialVersionUID = true;
            } catch (NoSuchFieldException e) {
                hasExplicitSerialVersionUID = false;
            }
        }
    }
}

From source file:info.raack.appliancelabeler.service.DefaultDataServiceTest.java

@Before
public void setup() throws SecurityException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException, JAXBException, SAXException {
    database = mock(Database.class);

    energyMonitor = mock(EnergyMonitor.class);
    oauthRequestProcessor = mock(OAuthRequestProcessor.class);
    detectionManager = mock(ApplianceDetectionManager.class);
    stepgreenBaseHost = "thebasehost";

    when(energyMonitor.getUserId()).thenReturn("theuserid");

    dataService = new DefaultDataService();
    Class<?> c = dataService.getClass();
    Field f = c.getDeclaredField("database");
    f.setAccessible(true);//from www .  j av  a2s.c o  m
    f.set(dataService, database);

    f = c.getDeclaredField("oAuthRequestProcessor");
    f.setAccessible(true);
    f.set(dataService, oauthRequestProcessor);

    f = c.getDeclaredField("stepgreenBasehost");
    f.setAccessible(true);
    f.set(dataService, stepgreenBaseHost);

    f = c.getDeclaredField("detectionManager");
    f.setAccessible(true);
    f.set(dataService, detectionManager);

    dataService.init();
}

From source file:cn.powerdash.libsystem.common.exception.AbstractExceptionHandler.java

/**
 * /* w w w . jav  a2  s .c  o m*/
 * 
 * @param rootClz
 * @param parseFieldName
 * @param matcher
 * @return
 * @throws SecurityException
 * @throws NoSuchFieldException
 */
private Class<?> getNextRootClass(Class<?> rootClz, final String parseFieldName, final boolean isFound)
        throws NoSuchFieldException, SecurityException {
    Class<?> rootClass = rootClz;
    if (rootClass != null) {
        try {
            Field parseField = rootClass.getDeclaredField(parseFieldName);
            if (isFound) {
                rootClass = (Class<?>) (((ParameterizedType) (parseField.getGenericType()))
                        .getActualTypeArguments())[0];
            } else {
                rootClass = parseField.getType();
            }
        } catch (NoSuchFieldException ex) {
            try {
                final Class<?> superClass = rootClass.getSuperclass();
                Field parseField = (superClass != null) ? superClass.getDeclaredField(parseFieldName) : null;
                if (parseField != null) {
                    if (isFound) {
                        rootClass = (Class<?>) (((ParameterizedType) (parseField.getGenericType()))
                                .getActualTypeArguments())[0];
                    } else {
                        rootClass = parseField.getType();
                    }
                }
            } catch (NoSuchFieldException ex1) {
                final Class<?> exsuperClass = rootClass.getSuperclass().getSuperclass();
                Field parseField = (exsuperClass != null) ? exsuperClass.getDeclaredField(parseFieldName)
                        : null;
                if (parseField != null) {
                    if (isFound) {
                        rootClass = (Class<?>) (((ParameterizedType) (parseField.getGenericType()))
                                .getActualTypeArguments())[0];
                    } else {
                        rootClass = parseField.getType();
                    }
                }
            }
        }
        LOGGER.debug("Next rootClass = " + rootClass);
        return rootClass;
    } else {
        return null;
    }
}

From source file:jp.gr.java_conf.petit_lycee.subsonico.MethodConstants.java

private Field getField(@SuppressWarnings("rawtypes") Class cls, String fieldName) throws NoSuchFieldException {
    try {/*  w  ww . j a va 2  s  .com*/
        return cls.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        @SuppressWarnings("rawtypes")
        Class super_cls = cls.getSuperclass();
        //????
        //??
        if (super_cls != null && super_cls.getPackage().equals(cls.getPackage())) {
            return getField(super_cls, fieldName);
        }
        throw e;
    }
}

From source file:net.avalonrealms.plugins.core.Core.java

@Override
public void onEnable() {
    // Folders/* w w w.  j a  v a 2s . c om*/
    downloadFolder = new File(getDataFolder(), "downloads");
    errorFolder = new File(getDataFolder(), "errors");
    addonFolder = new File(getDataFolder(), "addons");
    repoFolder = new File(getDataFolder(), "repo");

    // Make folders TODO check result
    downloadFolder.mkdirs();
    errorFolder.mkdirs();
    addonFolder.mkdirs();
    repoFolder.mkdirs();

    // Utils
    errorUtils = new ErrorUtils(this);
    hookUtils = new HookUtils(this);

    // Updater
    updater = new Updater(this);

    // CommandInfo map
    try {
        Class<?> craftServer = SVPTools.getCurrentCBClass("CraftServer");
        if (craftServer == null)
            throw new RuntimeException("Computer says no to getting the craft server");
        Field f = craftServer.getDeclaredField("commandMap");
        f.setAccessible(true);
        commandMap = (CommandMap) f.get(getServer());
    } catch (Exception e) {
        errorUtils.logError(e);
        getServer().getPluginManager().disablePlugin(this);
        return;
    }

    // Listeners
    PluginManager p = getServer().getPluginManager();

    if (getHookUtils().isHooked(HookUtils.Hook.WORLD_GUARD)) {
        p.registerEvents(new WGListener(this, (com.sk89q.worldguard.bukkit.WorldGuardPlugin) getHookUtils()
                .getHook(HookUtils.Hook.WORLD_GUARD)), this);
    } else {
        getLogger().warning("WorldGuard was not found. WorldGuard events will not run.");
    }

    // Addons
    File[] addons = getAddonFolder().listFiles();

    if (addons == null) {
        throw new RuntimeException("Unable to create addon directory");
    }

    for (File file : addons) {
        if (file.isDirectory() || !file.getName().endsWith(".jar")) {
            continue;
        }

        try {
            ClasspathTools.addFileToClasspath(getClassLoader(), file);

            JarFile jar = new JarFile(file);

            Class<?> main = Class.forName(jar.getManifest().getMainAttributes().getValue("Addon-Package"));
            CoreAddon addon = (CoreAddon) main.newInstance();
            addon.setManifestValues(jar.getManifest());
            coreAddons.put(addon.getName(), addon);

            jar.close();
        } catch (Exception e) {
            errorUtils.logError(e);
        }
    }

    for (CoreAddon addon : Maps.newHashMap(coreAddons).values()) {
        addon.initialise(this);
        addon.onEnable();
    }

    getLogger().info("Enabled " + coreAddons.size() + " addons.");
}

From source file:eu.earthobservatory.org.StrabonEndpoint.capabilities.AutoDiscoveryCapabilities.java

@Override
public boolean supportsLimit() {
    @SuppressWarnings("rawtypes")
    Class strabonWrapper;//from www  . ja  va  2 s.  c o m
    try {
        strabonWrapper = Class.forName("eu.earthobservatory.org.StrabonEndpoint.StrabonBeanWrapper");

        strabonWrapper.getDeclaredField("maxLimit");

        return true;

    } catch (ClassNotFoundException e1) {
        // No StrabonBeanWrapper? How come?
        logger.warn(
                "[StrabonEndpoint.AutoDiscoveryCapabilities] Didn't find StrabonEndpoint class!!! How come?");

    } catch (SecurityException e) {
        logger.info(
                "[StrabonEndpoint.AutoDiscoveryCapabilities] Could not determine limit support due to security exception. ",
                e);

    } catch (NoSuchFieldException e) {
        // this exception is OK. Strabon Endpoint does not support limit of results
    }

    return false;
}

From source file:com.smartitengineering.cms.spi.impl.content.GroovyGeneratorTest.java

protected void registerBeanFactory(final WorkspaceAPI api) {
    try {/*from  w w  w.j  a  v  a  2  s  .  c  o  m*/
        SmartContentAPI mainApi = SmartContentAPI.getInstance();
        Class apiClass = mainApi.getClass();
        java.lang.reflect.Field field = apiClass.getDeclaredField("workspaceApi");
        field.setAccessible(true);
        field.set(mainApi, api);
    } catch (Exception ex) {
        throw new IllegalArgumentException(ex);
    }
}

From source file:edu.purdue.cybercenter.dm.service.CqlService.java

private Object getPropertyValue(Object object, String propertyName)
        throws IllegalArgumentException, IllegalAccessException {
    Object value = null;//from ww  w.  j a v  a2 s.co m

    Class<?> objectClass = object.getClass();
    do {
        try {
            Field field = objectClass.getDeclaredField(propertyName);
            field.setAccessible(true);
            value = field.get(objectClass.cast(object));
            break;
        } catch (NoSuchFieldException ex) {
        }
    } while ((objectClass = objectClass.getSuperclass()) != null);

    return value;
}

From source file:cn.chenlichao.web.ssm.service.impl.BaseServiceImpl.java

private void processOrder(Example example, String orderBy, boolean isAsc) {
    Class<?> clazz = example.getEntityClass();
    try {/*from w w w  . j a v a  2s .co m*/
        Field field = clazz.getDeclaredField(orderBy);
        if (field != null) {
            Column column = field.getAnnotation(Column.class);
            if (column != null) {
                example.setOrderByClause(column.name() + (isAsc ? " ASC" : " DESC"));
                return;
            }
        }
    } catch (NoSuchFieldException e) {
        // do nothing
    }
    example.setOrderByClause(orderBy + (isAsc ? " ASC" : " DESC"));
}

From source file:LinkedTransferQueue.java

static long objectFieldOffset(sun.misc.Unsafe UNSAFE, String field, Class<?> klazz) {
    try {//from   w w  w .j  a v a  2s  .  c o  m
        return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
    } catch (NoSuchFieldException e) {
        // Convert Exception to corresponding Error
        NoSuchFieldError error = new NoSuchFieldError(field);
        error.initCause(e);
        throw error;
    }
}