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:com.netspective.axiom.sql.StoredProcedureParameter.java

/**
 * Database vendors implement the process of returning result set from a stored procedure
 * differently. This method will try to detect the database vendor through the driver name and
 * register the correct out parameter type specific to the vendor.
 * If it isn't able to guess the database from the drive name, it will return <code>Types.OTHER</code>
 * as the result set type.//from  w  w w . j a va 2s . c om
 *
 * @param cc connection context object
 *
 * @return the JDBC type code defined by <code>java.sql.Types</code>.
 */
public int getVendorSpecificResultSetType(ConnectionContext cc) {
    // set the default type
    int sqlType = Types.OTHER;
    try {
        if (isOracleDriver(cc)) {
            // ORACLE DRIVER
            Class oClass = Class.forName("oracle.jdbc.driver.OracleTypes");
            sqlType = oClass.getField("CURSOR").getInt(null);
        }
    } catch (Exception e) {
        log.error("Failed to get the column type for the result set cursor for stored procedure" + "'"
                + parent.getProcedure() + "'.");
    }
    return sqlType;
}

From source file:org.eclipse.wb.internal.core.editor.palette.PaletteManager.java

/**
 * Applies commands for modifying palette.
 *//*from   w  w w.ja  v a  2s.  c om*/
private void commands_apply() throws Exception {
    // prepare mapping: id -> command class
    if (m_idToCommandClass.isEmpty()) {
        for (Class<? extends Command> commandClass : m_commandClasses) {
            String id = (String) commandClass.getField("ID").get(null);
            m_idToCommandClass.put(id, commandClass);
        }
    }
    // read commands
    commandsRead();
}

From source file:com.oe.phonegap.plugins.AutoRecordVideo.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/*from   w w  w .  j  a 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:run.ace.NativeHost.java

void getAndroidId(String name, CallbackContext callbackContext) {
    Class c = null;
    try {// ww w .  j a v a 2  s .  c  o m
        c = Class.forName(_activity.getPackageName() + ".R$id");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(
                "Unable to find the R.id class in package '" + _activity.getPackageName() + "'");
    }

    int id;
    try {
        Field f = c.getField(name);
        id = (Integer) f.get(null);
    } catch (NoSuchFieldException ex) {
        throw new RuntimeException(c.getSimpleName() + " does not have a " + name + " field");
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(c.getSimpleName() + "'s " + name + " field is inaccessible");
    }

    callbackContext.success(id);
}

From source file:run.ace.NativeHost.java

View readAndroidXml(String layoutName) {
    Class c = null;
    try {/*from   w  ww .  j av a2 s.c  o m*/
        c = Class.forName(_activity.getPackageName() + ".R$layout");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(
                "Unable to find the R.layout class in package '" + _activity.getPackageName() + "'");
    }

    int id;
    try {
        Field f = c.getField(layoutName);
        id = (Integer) f.get(null);
    } catch (NoSuchFieldException ex) {
        throw new RuntimeException(c.getSimpleName() + " does not have a " + layoutName + " field");
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(c.getSimpleName() + "'s " + layoutName + " field is inaccessible");
    }

    return android.view.LayoutInflater.from(_activity).inflate(id, null);
}

From source file:hoot.services.controllers.job.JobResource.java

private JSONObject execReflectionSync(String jobId, String childJobId, JSONObject job,
        JobStatusManager jobStatusManager) throws Exception {
    String className = job.get("class").toString();
    String methodName = job.get("method").toString();

    String internalJobId = (job.get("internaljobid") == null) ? null : job.get("internaljobid").toString();

    JSONArray paramsList = (JSONArray) job.get("params");

    Class<?>[] paramTypes = new Class[paramsList.size()];
    Object[] parameters = new Object[paramsList.size()];
    for (int i = 0; i < paramsList.size(); i++) {
        JSONObject param = (JSONObject) paramsList.get(i);
        String paramType = param.get("paramtype").toString();
        Object oIsPrim = param.get("isprimitivetype");
        if ((oIsPrim != null) && oIsPrim.toString().equalsIgnoreCase("true")) {
            Class<?> classWrapper = Class.forName(paramType);
            paramTypes[i] = (Class<?>) classWrapper.getField("TYPE").get(null);
        } else {/*from   w w w. j  av a2  s . c  o m*/
            paramTypes[i] = Class.forName(paramType);
        }
        parameters[i] = param.get("value");
    }

    Class<?> clazz = Class.forName(className);
    Object instance = clazz.newInstance();

    JSONObject childJobInfo;
    String currentChildJobId = childJobId;

    // May be we would need create interface to guarranttee that it will
    // return a job id?  Add internal job id to end of method call
    if (internalJobId != null) {
        currentChildJobId = internalJobId;
        childJobInfo = createChildInfo(currentChildJobId, JOB_STATUS.RUNNING.toString());
        setJobInfo(jobInfo, childJobInfo, childrenInfo, JOB_STATUS.RUNNING.toString(), "processing");
        jobStatusManager.updateJob(jobId, jobInfo.toString());

        Object[] newParams = new Object[paramsList.size() + 1];
        System.arraycopy(parameters, 0, newParams, 0, parameters.length);
        newParams[parameters.length] = internalJobId;

        Class<?>[] newParamTypes = new Class[paramsList.size() + 1];
        System.arraycopy(paramTypes, 0, newParamTypes, 0, paramsList.size());
        newParamTypes[parameters.length] = String.class;
        Method method = clazz.getDeclaredMethod(methodName, newParamTypes);
        // This will blow if the method is not designed to handle job id
        method.invoke(instance, newParams);
    } else {
        Method method = clazz.getDeclaredMethod(methodName, paramTypes);
        Object oReflectJobId = method.invoke(instance, parameters);
        if (oReflectJobId != null) {
            currentChildJobId = oReflectJobId.toString();
        }

        // Updating job status info. Looks like we need to wait till job is
        // done to get job id. With this we can not canel..
        childJobInfo = createChildInfo(currentChildJobId, JobStatusManager.JOB_STATUS.RUNNING.toString());
        setJobInfo(jobInfo, childJobInfo, childrenInfo, JOB_STATUS.RUNNING.toString(), "processing");
        jobStatusManager.updateJob(jobId, jobInfo.toString());
    }

    return childJobInfo;
}

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

public static Field getField(Class<?> clazz, String fieldName) throws IOException {
    if (clazz == null)
        throw new IOException("clazz is null");
    if (fieldName == null)
        throw new IOException("fieldName is null");
    if (fieldName.isEmpty())
        throw new IOException("fieldName is empty");
    Field field = null;/*from  w  ww. ja v  a2  s.  co m*/
    try {
        field = clazz.getDeclaredField(fieldName);
    } catch (Throwable t0) {
        try {
            field = clazz.getField(fieldName);
        } catch (Throwable t1) {
            if (clazz.getSuperclass() != null) {
                field = getField(clazz.getSuperclass(), fieldName);
            } else
                throw new IOException("fail to get field for " + clazz.getName() + "." + fieldName, t1);
        }
    }
    field.setAccessible(true);
    return field;
}

From source file:org.springframework.beans.TypeConverterDelegate.java

private Object attemptToConvertStringToEnum(Class<?> requiredType, String trimmedValue,
        Object currentConvertedValue) {
    Object convertedValue = currentConvertedValue;

    if (Enum.class == requiredType && this.targetObject != null) {
        // target type is declared as raw enum, treat the trimmed value as <enum.fqn>.FIELD_NAME
        int index = trimmedValue.lastIndexOf(".");
        if (index > -1) {
            String enumType = trimmedValue.substring(0, index);
            String fieldName = trimmedValue.substring(index + 1);
            ClassLoader cl = this.targetObject.getClass().getClassLoader();
            try {
                Class<?> enumValueType = ClassUtils.forName(enumType, cl);
                Field enumField = enumValueType.getField(fieldName);
                convertedValue = enumField.get(null);
            } catch (ClassNotFoundException ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Enum class [" + enumType + "] cannot be loaded", ex);
                }/*from  w  w  w  .  java 2 s . c om*/
            } catch (Throwable ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Field [" + fieldName + "] isn't an enum value for type [" + enumType + "]",
                            ex);
                }
            }
        }
    }

    if (convertedValue == currentConvertedValue) {
        // Try field lookup as fallback: for JDK 1.5 enum or custom enum
        // with values defined as static fields. Resulting value still needs
        // to be checked, hence we don't return it right away.
        try {
            Field enumField = requiredType.getField(trimmedValue);
            ReflectionUtils.makeAccessible(enumField);
            convertedValue = enumField.get(null);
        } catch (Throwable ex) {
            if (logger.isTraceEnabled()) {
                logger.trace("Field [" + convertedValue + "] isn't an enum value", ex);
            }
        }
    }

    return convertedValue;
}

From source file:org.ebayopensource.turmeric.tools.errorlibrary.ErrorLibraryGeneratorTest.java

@Test
public void validateContentOfErrorConstants() throws Exception {
    String errorConstantsClassName = "org.ebayopensource.turmeric.test.errorlibrary.turmericruntime.ErrorConstants";
    String sampleErrorName = "svc_factory_custom_ser_no_bound_type";

    // Initialize testing paths
    MavenTestingUtils.ensureEmpty(testingdir);
    File rootDir = TestResourceUtil.copyResourceRootDir("errorLibrary/TestErrorLibrary", testingdir);
    File binDir = new File(rootDir, "bin");
    File gensrcDir = new File(rootDir, "gen-src");

    MavenTestingUtils.ensureDirExists(binDir);
    MavenTestingUtils.ensureDirExists(gensrcDir);

    // @formatter:off
    String pluginParameters[] = { "-gentype", "genTypeConstants", "-pr", rootDir.getAbsolutePath(), "-domain",
            "TurmericRuntime", "-errorlibname", "TestErrorLibrary" };
    // @formatter:on

    performDirectCodeGen(pluginParameters);

    Class<?> errConstant = compileGeneratedFile(errorConstantsClassName, gensrcDir, binDir);
    Assert.assertThat("errConstant", errConstant, notNullValue());
    Assert.assertThat(errConstant.getName(), is(errorConstantsClassName));

    Field member = errConstant.getField(sampleErrorName.toUpperCase());
    Assert.assertThat("member", member, notNullValue());
    Assert.assertThat("member.type", member.getType().getName(), is(String.class.getName()));
    Assert.assertThat("member.isFinal", Modifier.isFinal(member.getModifiers()), is(true));
    Assert.assertThat("member.isPublic", Modifier.isPublic(member.getModifiers()), is(true));
    Assert.assertThat("member.isStatic", Modifier.isStatic(member.getModifiers()), is(true));
    Assert.assertThat("member.get(null)", (String) member.get(null), is(sampleErrorName));
}

From source file:org.jboss.errai.ui.rebind.TranslationServiceGenerator.java

@Override
public String generate(TreeLogger logger, GeneratorContext context) {
    // The class we will be building is GeneratedTranslationService
    final ClassStructureBuilder<?> classBuilder = Implementations.extend(TranslationService.class,
            GENERATED_CLASS_NAME);/*ww w .j a  v  a 2 s .c o  m*/
    ConstructorBlockBuilder<?> ctor = classBuilder.publicConstructor();

    // The i18n keys found (per locale) while processing the bundles.
    Map<String, Set<String>> discoveredI18nMap = new HashMap<String, Set<String>>();

    // Find all fields annotated with @TranslationKey and generate code
    // in the c'tor to register each one as a translation key for the
    // default (null) locale. These values may get overridden by keys
    // found in the default bundle. This is why we do this before we do
    // the bundle work.
    Map<String, String> translationKeyFieldMap = new HashMap<String, String>();
    Collection<MetaField> translationKeyFields = ClassScanner.getFieldsAnnotatedWith(TranslationKey.class, null,
            context);
    for (MetaField metaField : translationKeyFields) {
        // Figure out the translation key name
        String name = null;
        String fieldName = metaField.getName();
        String defaultName = metaField.getDeclaringClass().getFullyQualifiedName() + "." + fieldName;
        if (!metaField.getType().isAssignableFrom(String.class)) {
            throw new GenerationException(
                    "Translation key fields must be of type java.lang.String: " + defaultName);
        }
        try {
            Class<?> asClass = metaField.getDeclaringClass().asClass();
            Field field = asClass.getField(fieldName);
            Object fieldVal = field.get(null);
            if (fieldVal == null) {
                throw new GenerationException("Translation key fields cannot be null: " + defaultName);
            }
            name = fieldVal.toString();
        } catch (Exception e) {
            log.warn("There was an error while processing a TranslationKey", e);
        }

        // Figure out the translation key value (for the null locale).
        String value = null;
        TranslationKey annotation = metaField.getAnnotation(TranslationKey.class);
        String defaultValue = annotation.defaultValue();
        if (defaultValue != null) {
            value = defaultValue;
        } else {
            value = "!!" + defaultName + "!!";
        }

        // Generate code to register the null locale mapping
        if (translationKeyFieldMap.containsKey(name)) {
            throw new GenerationException("Duplicate translation key found: " + defaultName);
        }
        translationKeyFieldMap.put(name, value);
        ctor.append(Stmt.loadVariable("this").invoke("registerTranslation", name, value, null));
    }

    // Scan for all @Bundle annotations.
    final Collection<MetaClass> bundleAnnotatedClasses = ClassScanner.getTypesAnnotatedWith(Bundle.class,
            context);

    Set<String> bundlePaths = new HashSet<String>();
    for (MetaClass bundleAnnotatedClass : bundleAnnotatedClasses) {
        String bundlePath = getMessageBundlePath(bundleAnnotatedClass);
        bundlePaths.add(bundlePath);
    }

    // Now get all files in the message bundle (all localized versions)
    final Collection<URL> scannableUrls = getScannableUrls(bundleAnnotatedClasses);
    log.info("Preparing to scan for i18n bundle files.");
    MessageBundleScanner scanner = new MessageBundleScanner(
            new ConfigurationBuilder().filterInputsBy(new FilterBuilder().include(".*json"))
                    .setUrls(scannableUrls).setScanners(new MessageBundleResourceScanner(bundlePaths)));

    // For each one, generate the code to load the translation and put that generated
    // code in the c'tor of the generated class (GeneratedTranslationService)
    Collection<String> resources = scanner.getStore().get(MessageBundleResourceScanner.class).values();
    for (String bundlePath : bundlePaths) {
        // If we didn't find at least the specified root bundle file, that's a problem.
        if (!resources.contains(bundlePath)) {
            throw new GenerationException("Missing i18n bundle (specified in @Bundle): " + bundlePath);
        }
    }

    // Now generate code to load up each of the JSON files and register them
    // with the translation service.
    for (String resource : resources) {
        // Generate this component's ClientBundle resource interface
        BuildMetaClass messageBundleResourceInterface = generateMessageBundleResourceInterface(resource);
        // Add it as an inner class to the generated translation service
        classBuilder.getClassDefinition().addInnerClass(new InnerClass(messageBundleResourceInterface));

        // Instantiate the ClientBundle MessageBundle resource
        final String msgBundleVarName = InjectUtil.getUniqueVarName();
        ctor.append(Stmt.declareVariable(messageBundleResourceInterface).named(msgBundleVarName)
                .initializeWith(Stmt.invokeStatic(GWT.class, "create", messageBundleResourceInterface)));

        // Create a dictionary from the message bundle and register it.
        String locale = getLocaleFromBundlePath(resource);
        ctor.append(Stmt.loadVariable("this").invoke("registerBundle",
                Stmt.loadVariable(msgBundleVarName).invoke("getContents").invoke("getText"), locale));

        recordBundleKeys(discoveredI18nMap, locale, resource);
    }

    // We're done generating the c'tor
    ctor.finish();

    generateI18nHelperFilesInto(discoveredI18nMap, translationKeyFieldMap, RebindUtils.getErraiCacheDir());

    return classBuilder.toJavaString();
}