Java Code Examples for java.lang.reflect.Field

The following are top voted examples for showing how to use java.lang.reflect.Field. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: AndroidNClassLoader.java   View source code 7 votes vote down vote up
private static AndroidNClassLoader createAndroidNClassLoader(PathClassLoader originalClassLoader, Application application) throws Exception {
    //let all element ""
    final AndroidNClassLoader androidNClassLoader = new AndroidNClassLoader("",  originalClassLoader, application);
    final Field pathListField = ShareReflectUtil.findField(originalClassLoader, "pathList");
    final Object originPathList = pathListField.get(originalClassLoader);

    // To avoid 'dex file register with multiple classloader' exception on Android O, we must keep old
    // dexPathList in original classloader so that after the newly loaded base dex was bound to
    // AndroidNClassLoader we can still load class in base dex from original classloader.

    Object newPathList = recreateDexPathList(originPathList, androidNClassLoader);

    // Update new classloader's pathList.
    pathListField.set(androidNClassLoader, newPathList);

    return androidNClassLoader;
}
 
Example 2
Project: HTAPBench   File: Procedure.java   View source code 7 votes vote down vote up
protected static Map<String, SQLStmt> getStatments(Procedure proc) {
    Class<? extends Procedure> c = proc.getClass();
    Map<String, SQLStmt> stmts = new HashMap<String, SQLStmt>();
    for (Field f : c.getDeclaredFields()) {
        int modifiers = f.getModifiers();
        if (Modifier.isTransient(modifiers) == false &&
            Modifier.isPublic(modifiers) == true &&
            Modifier.isStatic(modifiers) == false) {
            try {
                Object o = f.get(proc);
                if (o instanceof SQLStmt) {
                    stmts.put(f.getName(), (SQLStmt)o);
                }
            } catch (Exception ex) {
                throw new RuntimeException("Failed to retrieve " + f + " from " + c.getSimpleName(), ex);
            }
        }
    } // FOR
    return (stmts);
}
 
Example 3
Project: randomito-all   File: AnnotationPostProcessorScanner.java   View source code 6 votes vote down vote up
public PostProcessor[] scan(final Object instance) {
    return FluentIterable
            .from(ReflectionUtils.getDeclaredFields(instance.getClass(), true))
            .filter(new Predicate<Field>() {
                @Override
                public boolean apply(Field input) {
                    return input.isAnnotationPresent(Random.PostProcessor.class)
                            && PostProcessor.class.isAssignableFrom(input.getType());
                }
            })
            .transform(new Function<Field, PostProcessor>() {
                @Override
                public PostProcessor apply(Field field) {
                    try {
                        if (!ReflectionUtils.makeFieldAccessible(field)) {
                            return null;
                        }
                        return (PostProcessor) field.get(instance);
                    } catch (IllegalAccessException e) {
                        throw new RandomitoException(e);
                    }
                }
            })
            .filter(Predicates.<PostProcessor>notNull())
            .toArray(PostProcessor.class);
}
 
Example 4
Project: openjdk-jdk10   File: LIRIntrospection.java   View source code 6 votes vote down vote up
@Override
protected void scanField(Field field, long offset) {
    Class<?> type = field.getType();
    if (VALUE_CLASS.isAssignableFrom(type) && !CONSTANT_VALUE_CLASS.isAssignableFrom(type)) {
        assert !Modifier.isFinal(field.getModifiers()) : "Value field must not be declared final because it is modified by register allocator: " + field;
        OperandModeAnnotation annotation = getOperandModeAnnotation(field);
        assert annotation != null : "Field must have operand mode annotation: " + field;
        EnumSet<OperandFlag> flags = getFlags(field);
        assert verifyFlags(field, type, flags);
        annotation.values.add(new ValueFieldInfo(offset, field.getName(), type, field.getDeclaringClass(), flags));
        annotation.directCount++;
    } else if (VALUE_ARRAY_CLASS.isAssignableFrom(type)) {
        OperandModeAnnotation annotation = getOperandModeAnnotation(field);
        assert annotation != null : "Field must have operand mode annotation: " + field;
        EnumSet<OperandFlag> flags = getFlags(field);
        assert verifyFlags(field, type.getComponentType(), flags);
        annotation.values.add(new ValueFieldInfo(offset, field.getName(), type, field.getDeclaringClass(), flags));
    } else {
        assert getOperandModeAnnotation(field) == null : "Field must not have operand mode annotation: " + field;
        assert field.getAnnotation(LIRInstruction.State.class) == null : "Field must not have state annotation: " + field;
        super.scanField(field, offset);
    }
}
 
Example 5
Project: AlphaLibary   File: ReflectionHelper.java   View source code 6 votes vote down vote up
public static SaveField[] findFieldsNotAnnotatedWith(Class<? extends Annotation> annotation, Class<?>... classes) {
    List<SaveField> fields = new LinkedList<>();
    int i = 0;

    for (Class<?> clazz : classes) {
        for (Field f : clazz.getDeclaredFields()) {
            if (!f.isAnnotationPresent(annotation)) {
                fields.add(new SaveField(f, i));
            }
            i++;
        }
        i = 0;
    }

    return fields.toArray(new SaveField[fields.size()]);
}
 
Example 6
Project: atlas   File: RemoteActivityManager.java   View source code 6 votes vote down vote up
public EmbeddedActivityRecord startEmbeddedActivity(String bundleName) throws Exception{
    EmbeddedActivityRecord activityRecord = new EmbeddedActivityRecord();
    activityRecord.id = "embedded_"+mParent.getClass().getSimpleName();
    Field mThemeResourceF = AndroidHack.findField(mParent,"mThemeResource");
    int mThemeResource = (Integer)mThemeResourceF.get(mParent);
    Intent intent = new Intent();
    intent.setClassName(mParent,EmbeddedActivity.class.getName());
    intent.putExtra("themeId",mThemeResource);
    intent.putExtra("bundleName",bundleName);
    ActivityInfo info = intent.resolveActivityInfo(mParent.getPackageManager(), PackageManager.GET_ACTIVITIES);
    activityRecord.activity = (EmbeddedActivity) ActivityThread_startActivityNow.invoke(AndroidHack.getActivityThread(),
            mParent, activityRecord.id, intent, info, activityRecord.activity, null, null);
    activityRecord.activityInfo = info;
    return activityRecord;
}
 
Example 7
Project: Shuriken   File: ClassWrapper.java   View source code 6 votes vote down vote up
/**
 * Get class field
 *
 * @param fieldName Field's name
 * @param type Field's type class
 * @param <V> Field's type
 * @return {@link FieldWrapper} object or empty, if field wasn't found
 */
@Contract("null, null -> fail")
@SuppressWarnings("unchecked")
public <V> Optional<FieldWrapper<V>> getField(String fieldName, Class<V> type) {
    /* Check arguments */
    if(fieldName == null) throw new IllegalStateException("Field name shouldn't be null!");
    if(type == null) throw new IllegalStateException("Field type shouldn't be null!");

    /* Try to find cached field */
    FieldInfo fieldInfo = new FieldInfo(fieldName, type);

    /* Get field */
    Integer found = FIELD_INDEX.get(fieldInfo);
    Field[] field = new Field[] { found != null ? FIELD_CACHE.get(found) : null };
    field[0] = field[0] != null ? field[0] : findDeclaredField(fieldName, type);
    if(field[0] == null) return Optional.empty();

    /* Wrap field */
    return Optional.of((FieldWrapper<V>)FIELDWRAPPER_CACHE.computeIfAbsent(found,
            k -> MethodHandleFieldWrapper.of(this, field[0], type)));
}
 
Example 8
Project: olingo-jpa   File: JpaOlingoEntity.java   View source code 6 votes vote down vote up
@Override
public List<Property> getProperties() {
    if (proxy.properties == null) {
        proxy.properties = new ArrayList<>();
        proxy.propertyAccessors = new HashMap<>();
        for (Field f : getAccessibleFields()) {
            ODataProperty annotation = f.getAnnotation(ODataProperty.class);
            if (annotation != null) {
                String name = annotation.name();
                RealAccessors<JpaOlingoEntity> accessors = new RealAccessors<>(this, f);
                proxy.properties.add(new Property(null, name, annotation.valueType(), accessors.get(this)));
                proxy.propertyAccessors.put(name, accessors);
            }
        }
    }
    return proxy.properties;
}
 
Example 9
Project: otter-G   File: PipelineParameter.java   View source code 6 votes vote down vote up
/**
 * 合并pipeline参数设置
 */
public void merge(PipelineParameter pipelineParameter) {
    try {
        Field[] fields = this.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            // Skip static and final fields.
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                continue;
            }

            ReflectionUtils.makeAccessible(field);
            Object srcValue = field.get(pipelineParameter);
            if (srcValue != null) { // 忽略null值
                field.set(this, srcValue);
            }
        }
    } catch (Exception e) {
        // ignore
    }
}
 
Example 10
Project: YuiHatano   File: ShadowResources.java   View source code 6 votes vote down vote up
protected Map<Integer, String> getIdTable(@RTypes String resName) throws IllegalAccessException, ClassNotFoundException {
    // R资源类全称
    String rClassName = mPackageName + ".R$" + resName;

    if (mResourceCache.hasIdTableCache(rClassName)) {
        return mResourceCache.getIdTableCache(rClassName);
    }

    Class                stringRClass = Class.forName(rClassName);
    Field[]              fields       = stringRClass.getDeclaredFields();
    Map<Integer, String> idTable      = new HashMap<>();
    for (Field field : fields) {
        field.setAccessible(true);

        int    id   = (int) field.get(null);
        String name = field.getName();

        idTable.put(id, name);
    }

    mResourceCache.cacheIdTable(rClassName, idTable);

    return idTable;
}
 
Example 11
Project: hibernateMaster   File: DomainUtil.java   View source code 6 votes vote down vote up
/**
 * 获取实体类ID Class
 * @param clazz
 * @return
 */
@SuppressWarnings("unchecked")
public static Class<? extends Serializable> getDomainIDClass(Class<? extends BaseDomain> clazz){
	/**
	 * 如果是联合主键实体类则返回domainID,因为联合主键类必须实现getDomainID()方法
	 */
	IdClass annotation = clazz.getAnnotation(IdClass.class);
	if (annotation != null) {
		return annotation.value();
	}
	try {
		Field f = ReflectUtil.getDeclaredField(clazz, getDomainIDName(clazz));
		if (f != null) {
			return (Class<? extends Serializable>) f.getType();
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw createFindIdException(clazz, e);
	}  
	throw createIDNotfoundException(clazz);
}
 
Example 12
Project: nixmash-blog   File: SiteOptions.java   View source code 6 votes vote down vote up
@PostConstruct
public void init() throws
        IllegalAccessException, NoSuchMethodException, InvocationTargetException {

    Collection<SiteOption> siteOptionKeyValues = siteOptionRepository.findAll();

    Map<String, Object> options = new Hashtable<>();
    for (SiteOption siteOption : siteOptionKeyValues) {
        options.put(siteOption.getName(), siteOption.getValue());
    }
    for (String key : options.keySet()) {
        for (Field f : this.getClass().getDeclaredFields()) {
            if (f.getName().toUpperCase().equals(key.toUpperCase())) {
                setSiteOptionProperty(key, options.get(key));
            }
        }
    }
}
 
Example 13
Project: xbot_head   File: ROSBridgeWebSocketClient.java   View source code 6 votes vote down vote up
@Override
public void closeBlocking() throws InterruptedException {
    super.closeBlocking();
    try {
        Field channelField = this.getClass().getSuperclass().getDeclaredField("channel");
        channelField.setAccessible(true);
        SocketChannel channel = (SocketChannel) channelField.get(this);
        if (channel != null && channel.isOpen()) {
            Socket socket = channel.socket();
            if (socket != null)
                    socket.close();
        }
    }
    catch (Exception ex) {
        System.out.println("Exception in Websocket close hack.");
        ex.printStackTrace();
    }
}
 
Example 14
Project: solo-spring   File: Reflections.java   View source code 6 votes vote down vote up
public static Set<Field> getHiddenFields(final Class<?> clazz) {
	final Field[] fields = clazz.getDeclaredFields();
	final Set<Field> declaredFieldSet = CollectionUtils.arrayToSet(fields);
	final Set<Field> ret = new HashSet<>();

	Class<?> currentClass = clazz.getSuperclass();

	while (currentClass != null) {
		final Field[] superFields = currentClass.getDeclaredFields();

		for (Field superField : superFields) {
			final Field match = getMatch(declaredFieldSet, superField);

			if (!Modifier.isPrivate(superField.getModifiers()) && !Modifier.isStatic(superField.getModifiers())
					&& match != null) {
				ret.add(match);
			}
		}
		currentClass = currentClass.getSuperclass();
	}

	return ret;
}
 
Example 15
Project: athena   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Sets the field, bypassing scope restriction.
 *
 * @param subject Object where the field belongs
 * @param fieldName name of the field to set
 * @param value value to set to the field.
 * @param <T> subject type
 * @param <U> value type
 * @throws TestUtilsException if there are reflection errors while setting
 * the field
 */
public static <T, U> void setField(T subject, String fieldName, U value)
        throws TestUtilsException {
    @SuppressWarnings("unchecked")
    Class clazz = subject.getClass();
    try {
        while (clazz != null) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(subject, value);
                break;
            } catch (NoSuchFieldException ex) {
                if (clazz == clazz.getSuperclass()) {
                    break;
                }
                clazz = clazz.getSuperclass();
            }
        }
    } catch (SecurityException | IllegalArgumentException |
             IllegalAccessException e) {
        throw new TestUtilsException("setField failed", e);
    }
}
 
Example 16
Project: febit   File: ArangoUtil.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static ArangoLinkInfo[] collectInfosIfAbsent(Class type) {
    ArangoLinkInfo[] infos = LINKS_CACHING.get(type);
    if (infos != null) {
        return infos;
    }

    final List<ArangoLinkInfo> list = new ArrayList<>();
    for (Field field : ClassUtil.getMemberFields(type)) {
        if (field.getType() != String.class) {
            continue;
        }
        ArangoLink linkAnno = field.getAnnotation(ArangoLink.class);
        if (linkAnno == null) {
            continue;
        }
        ClassUtil.setAccessible(field);
        Class<Entity> linkType = linkAnno.value();
        Class<?> serviceClass = linkAnno.service() != Object.class ? linkAnno.service()
                : linkType.getAnnotation(ArangoLink.class).value();

        list.add(new ArangoLinkInfo(((ArangoService) Services.get(serviceClass)).getDao(), field, linkType));
    }
    infos = list.isEmpty() ? EMPTY_LINKS : list.toArray(new ArangoLinkInfo[list.size()]);
    return LINKS_CACHING.putIfAbsent(type, infos);
}
 
Example 17
Project: serviceconnector   File: ServiceConnector.java   View source code 6 votes vote down vote up
/**
 * Search for the fields marked with @{@link ServiceInfo}
 */
private void initServiceHandlers(Class targetClass, Object target, Context context) throws IllegalArgumentException {
    Field[] fields = targetClass.getDeclaredFields();
    for (Field field : fields) {
        ServiceInfo serviceInfo = field.getAnnotation(ServiceInfo.class);
        if (serviceInfo != null) {
            if (IInterface.class.isAssignableFrom(field.getType())) {
                addServiceHandler(serviceInfo, (Class<? extends IInterface>) field.getType(), context);
                addFieldInfo(serviceInfo, field, target);
            } else if (isRemoter(field.getType())) {
                addRemoterServiceHandler(serviceInfo, field.getType(), context);
                addFieldInfo(serviceInfo, field, target);

            } else {
                throw new IllegalArgumentException(field.getName() + " is not a field of type IInterface or Remoter");
            }
        }
    }
}
 
Example 18
Project: BestPracticeApp   File: PointView.java   View source code 6 votes vote down vote up
public static int getStatusBarHeight(Context context) {
    Class<?> c = null;
    Object obj = null;
    Field field = null;
    int x = 0, statusBarHeight = 0;
    try {
        c = Class.forName("com.android.internal.R$dimen");
        obj = c.newInstance();
        field = c.getField("status_bar_height");
        x = Integer.parseInt(field.get(obj).toString());
        statusBarHeight = context.getResources().getDimensionPixelSize(x);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    return statusBarHeight;
}
 
Example 19
Project: jdk8u-jdk   File: AWTEvent.java   View source code 6 votes vote down vote up
/**
 * Copies all private data from this event into that.
 * Space is allocated for the copied data that will be
 * freed when the that is finalized. Upon completion,
 * this event is not changed.
 */
void copyPrivateDataInto(AWTEvent that) {
    that.bdata = this.bdata;
    // Copy canAccessSystemClipboard value from this into that.
    if (this instanceof InputEvent && that instanceof InputEvent) {
        Field field = get_InputEvent_CanAccessSystemClipboard();
        if (field != null) {
            try {
                boolean b = field.getBoolean(this);
                field.setBoolean(that, b);
            } catch(IllegalAccessException e) {
                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                    log.fine("AWTEvent.copyPrivateDataInto() got IllegalAccessException ", e);
                }
            }
        }
    }
    that.isSystemGenerated = this.isSystemGenerated;
}
 
Example 20
Project: B4zV4lidator   File: B4zV4lidatorUtil.java   View source code 6 votes vote down vote up
public static Method getMethod(final Object obj, final Field field) {
	Method method = null;
	final String fieldName = field.getName();
	final String methodName = "get" + StringUtils.capitalize(fieldName);
	try {
		method = obj.getClass().getDeclaredMethod(methodName.trim(), new Class<?>[0]);
		method.setAccessible(true);
	} catch (NoSuchMethodException | SecurityException e) {
		final String[] splitedReturnType = field.getType().getName().split("\\.");
		final int splitedReturnTypeLength = splitedReturnType.length - 1;
		B4zV4lidatorUtil.LOGGER.severe("The attribute " + fieldName
				+ " cannot be validated because it has not a well formed getter method. This method should be like: \n\n\tpublic "
				+ splitedReturnType[splitedReturnTypeLength] + " " + methodName + "() {\n" + "\n"
				+ "		return this." + fieldName + ";\n" + "	}");
	}
	return method;
}
 
Example 21
Project: businessworks   File: Errors.java   View source code 6 votes vote down vote up
public static void formatInjectionPoint(Formatter formatter, Dependency<?> dependency,
    InjectionPoint injectionPoint, ElementSource elementSource) {
  Member member = injectionPoint.getMember();
  Class<? extends Member> memberType = Classes.memberType(member);

  if (memberType == Field.class) {
    dependency = injectionPoint.getDependencies().get(0);
    formatter.format("  while locating %s%n", convert(dependency.getKey(), elementSource));
    formatter.format("    for field at %s%n", StackTraceElements.forMember(member));

  } else if (dependency != null) {
    formatter.format("  while locating %s%n", convert(dependency.getKey(), elementSource));
    formatter.format("    for %s%n", formatParameter(dependency));

  } else {
    formatSource(formatter, injectionPoint.getMember());
  }
}
 
Example 22
Project: s-store   File: TestDesignerHints.java   View source code 6 votes vote down vote up
public void testSerialization() throws Exception {
        hints.limit_local_time = 1000;
        hints.limit_total_time = 9999;
        hints.ignore_procedures.add("neworder");
        
        File temp = FileUtil.getTempFile("hints", true);
        System.err.println(temp);
        hints.save(temp);

        DesignerHints clone = new DesignerHints();
        clone.load(temp, null);
        
        for (Field f : hints.getClass().getFields()) {
            Object expected = f.get(hints);
            Object actual = f.get(clone);
//            System.err.println(String.format("%s => %s / %s", f.getName(), expected, actual));
            assertEquals(f.getName(), expected, actual);
        } // FOR
    }
 
Example 23
Project: classchecks   File: SelfServletContextListener.java   View source code 5 votes vote down vote up
/**
 * 卸载已经装载的dll
 * 
 * @param dllName
 *            库名,如Decode.dll
 **/
@SuppressWarnings({ "unchecked", "unused" })
private synchronized void freeDll(String dllName) {
	try {
		ClassLoader classLoader = this.getClass().getClassLoader();
		Field field = ClassLoader.class.getDeclaredField("nativeLibraries");
		field.setAccessible(true);
		Vector<Object> libs = (Vector<Object>) field.get(classLoader);
		Iterator<Object> it = libs.iterator();
		Object o;

		while (it.hasNext()) {
			o = it.next();
			Field[] fs = o.getClass().getDeclaredFields();
			boolean hasInit = false;
			for (int k = 0; k < fs.length; k++) {
				if (fs[k].getName().equals("name")) {
					fs[k].setAccessible(true);
					String dllPath = fs[k].get(o).toString();
					if (dllPath.endsWith(dllName)) {
						hasInit = true;
					}
				}
			}
			if (hasInit) {
				Method finalize = o.getClass().getDeclaredMethod("finalize", new Class[0]);
				finalize.setAccessible(true);
				finalize.invoke(o, new Object[0]);
				it.remove();
				libs.remove(o);
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 24
Project: dremio-oss   File: TestAccelerationFailures.java   View source code 5 votes vote down vote up
@BeforeClass
public static void setupBeforeClass() throws Exception {
  BaseTestServer.init();

  // Add custom PipelineFactory that replaces each stage with dummy stages that can fail.
  final AccelerationService service = (AccelerationService) l(AccelerationService.class);
  Field pipeManagerField = service.getClass().getDeclaredField("pipelineManager");
  pipeManagerField.setAccessible(true);
  PipelineManager pipeManager = (PipelineManager) pipeManagerField.get(service);
  Field pipeFactoryField = pipeManager.getClass().getDeclaredField("factory");
  pipeFactoryField.setAccessible(true);
  pipeFactoryField.set(pipeManager, new TestPipelineFactory());
}
 
Example 25
Project: jarling   File: AddressesDeserializer.java   View source code 5 votes vote down vote up
private void assignAddress(Object addressesInstance, JsonElement jsonAddress, String member){

        Field addressesField;
        try {
            addressesField = addressesInstance.getClass().getDeclaredField(member);
            addressesField.setAccessible(true);
            if (jsonAddress == null){
                addressesField.set(addressesInstance, Address.class.newInstance());
            }else {
                addressesField.set(addressesInstance, gson.fromJson(jsonAddress, Address.class));
            }
        } catch (NoSuchFieldException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
 
Example 26
Project: stock-api-sdk   File: SearchParametersTest.java   View source code 5 votes vote down vote up
@Test(groups = { "Setters" })
void setFilterEditorial_should_set_media_Filter_Editorial_and_should_return_instanceof_SearchParameters()
        throws IllegalAccessException,
        NoSuchFieldException {
    Assert.assertNotNull(param.setFilterEditorial(true));
    Field f = param.getClass().getDeclaredField("mFilterEditorial");
    f.setAccessible(true);
    Assert.assertTrue((f.get(param)).equals(true));
}
 
Example 27
Project: lambda-monitoring   File: MetricsFinder.java   View source code 5 votes vote down vote up
public Map<String, Field> find() throws MalformedURLException {

        Reflections reflections = new Reflections(
                new ConfigurationBuilder()
                        .setUrls(classpathUrls)
                        .addClassLoader(new URLClassLoader(classpathUrls.toArray(new URL[0]), getClass().getClassLoader()))
                        .setScanners(new SubTypesScanner()));

        Map<String, Field> metricFields = new HashMap<>();
        for (Class<? extends LambdaMetricSet> type : reflections.getSubTypesOf(LambdaMetricSet.class)) {
            metricFields.putAll(MetricsUtils.findAnnotatedFields(type));
        }

        return metricFields;
    }
 
Example 28
Project: stock-api-sdk   File: LicensePurchaseDetailsTest.java   View source code 5 votes vote down vote up
@Test(groups = { "Setters" })
void setFrameRate_should_set_FrameRate_of_Type_Double_LicensePurchaseDetails()
        throws NoSuchFieldException, IllegalAccessException {
    purchaseDetails.setFrameRate(100.1);
    Field f = purchaseDetails.getClass().getDeclaredField("mFrameRate");
    f.setAccessible(true);
    Assert.assertTrue(f.get(purchaseDetails).equals(100.1));
}
 
Example 29
Project: TYT   File: HomeFragment.java   View source code 5 votes vote down vote up
/**
 * 通过文件名获取资源id 例子:getResId("icon", R.drawable.class);
 *
 * @param variableName
 * @param c
 * @return
 */
private static int getResId(String variableName, Class<?> c) {
    try {
        Field idField = c.getDeclaredField(variableName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}
 
Example 30
Project: monarch   File: KerberosUtils.java   View source code 5 votes vote down vote up
public static Oid getOidInstance(String oidName)
    throws ClassNotFoundException, GSSException, NoSuchFieldException, IllegalAccessException {
  Class<?> oidClass;
  if (IBM_JAVA) {
    if ("NT_GSS_KRB5_PRINCIPAL".equals(oidName)) {
      // IBM JDK GSSUtil class does not have field for krb5 principal oid
      return new Oid("1.2.840.113554.1.2.2.1");
    }
    oidClass = Class.forName("com.ibm.security.jgss.GSSUtil");
  } else {
    oidClass = Class.forName("sun.security.jgss.GSSUtil");
  }
  Field oidField = oidClass.getDeclaredField(oidName);
  return (Oid) oidField.get(oidClass);
}
 
Example 31
Project: qpp-conversion-tool   File: PathCorrelatorTest.java   View source code 5 votes vote down vote up
@Test
void pathCorrelatorInitilizationNegative() throws Throwable {
	Field configPath = PathCorrelator.class.getDeclaredField("config");
	configPath.setAccessible(true);
	configPath.set(null, "meep.json");

	Method method = PathCorrelator.class.getDeclaredMethod("loadPathCorrelation");
	method.setAccessible(true);

	InvocationTargetException ex = assertThrows(InvocationTargetException.class, () -> method.invoke(null));
	assertThat(ex).hasCauseThat().isInstanceOf(PathCorrelationException.class);
}
 
Example 32
Project: ditb   File: TestFSHLog.java   View source code 5 votes vote down vote up
@Test
public void testSyncRunnerIndexOverflow() throws IOException, NoSuchFieldException,
    SecurityException, IllegalArgumentException, IllegalAccessException {
  final String name = "testSyncRunnerIndexOverflow";
  FSHLog log =
      new FSHLog(fs, FSUtils.getRootDir(conf), name, HConstants.HREGION_OLDLOGDIR_NAME, conf,
          null, true, null, null);
  try {
    Field ringBufferEventHandlerField = FSHLog.class.getDeclaredField("ringBufferEventHandler");
    ringBufferEventHandlerField.setAccessible(true);
    FSHLog.RingBufferEventHandler ringBufferEventHandler =
        (FSHLog.RingBufferEventHandler) ringBufferEventHandlerField.get(log);
    Field syncRunnerIndexField =
        FSHLog.RingBufferEventHandler.class.getDeclaredField("syncRunnerIndex");
    syncRunnerIndexField.setAccessible(true);
    syncRunnerIndexField.set(ringBufferEventHandler, Integer.MAX_VALUE - 1);
    HTableDescriptor htd =
        new HTableDescriptor(TableName.valueOf("t1")).addFamily(new HColumnDescriptor("row"));
    HRegionInfo hri =
        new HRegionInfo(htd.getTableName(), HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
    MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
    for (int i = 0; i < 10; i++) {
      addEdits(log, hri, htd, 1, mvcc);
    }
  } finally {
    log.close();
  }
}
 
Example 33
Project: stock-api-sdk   File: SearchParametersTest.java   View source code 5 votes vote down vote up
@Test(groups = { "Getters" })
void getSimilarId_should_return_media_Similar_id_of_Type_Integer()
        throws NoSuchFieldException,
        IllegalAccessException {
    Assert.assertTrue(param.getSimilar() == null);
    Field f = param.getClass().getDeclaredField("mSimilar");
    f.setAccessible(true);
    f.set(param, 127);
    Assert.assertEquals(127, param.getSimilar().intValue());
}
 
Example 34
Project: stock-api-sdk   File: LicenseThumbnailTest.java   View source code 5 votes vote down vote up
@Test(groups = { "Getters" })
void getWidth_should_return_width_of_Type_Integer_LicenseThumbnail()
        throws NoSuchFieldException, IllegalAccessException {
    Field f = thumbnail.getClass().getDeclaredField("mWidth");
    f.setAccessible(true);
    f.set(thumbnail, 100);
    Assert.assertTrue(thumbnail.getWidth().equals(100));
}
 
Example 35
Project: zeratul   File: ReflectionUtils.java   View source code 5 votes vote down vote up
/**
 * 获取属性值
 * @param bean        实例
 * @param targetClass 属性所属class
 * @param fieldName   属性名
 * @return Field
 * @throws IllegalAccessException .{@link IllegalAccessException}
 */
public static Field getField(Object bean, Class targetClass, String fieldName) throws IllegalAccessException {
    List<Field> fields = Lists.newArrayList();
    getAllFields(bean.getClass(), fields);
    // 第一次类型和属性名都满足才返回
    Optional<Field> oneNewFields = fields.stream()
            .filter(field -> field.getName().equals(fieldName) && field.getType() == targetClass)
            .findFirst();
    // 第2次类型和属性名满足一个即返回
    Optional<Field> twoNewFields = fields.stream()
            .filter(field -> field.getName().equals(fieldName) || field.getType() == targetClass)
            .findFirst();
    return oneNewFields.orElseGet(() -> twoNewFields.orElse(null));
}
 
Example 36
Project: spring-data-generator   File: RepositoryStructure.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Tuple<String, Boolean> getEntityId(String entityClass){
    try {
        Class<?> entity = null;
        if (loader == null) {
            entity = Class.forName(entityClass);
        } else {
            entity = loader.getUrlClassLoader().loadClass(entityClass);
        }

        while (entity != null){
            for (Field field : entity.getDeclaredFields()) {
                if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) {
                    this.implementsSerializable(field.getType());
                    return new Tuple<>(field.getType().getName(), this.isCustomType(field.getType()));
                }
            }

            for (Method method : entity.getDeclaredMethods()) {
                if (!method.getReturnType().equals(Void.TYPE) && (method.isAnnotationPresent(Id.class) || method.isAnnotationPresent(EmbeddedId.class))) {
                    this.implementsSerializable(method.getReturnType());
                    return new Tuple<>(method.getReturnType().getName(), this.isCustomType(method.getReturnType()));
                }
            }
            entity = entity.getSuperclass();
        }

        error = SDLogger.addError("Repository Error: Primary key not found in " + GeneratorUtils.getSimpleClassName(entityClass) + ".java");
        return null;
    } catch (GeneratorException ex) {
        error = SDLogger.addError(ex.getMessage());
        return null;
    } catch (Exception e) {
        error = SDLogger.addError("Repository Error: Failed to access entity " + GeneratorUtils.getSimpleClassName(entityClass) + ".java");
        return null;
    }
}
 
Example 37
Project: android-dev-challenge   File: TestUtilities.java   View source code 5 votes vote down vote up
static String getStaticStringField(Class clazz, String variableName)
        throws NoSuchFieldException, IllegalAccessException {
    Field stringField = clazz.getDeclaredField(variableName);
    stringField.setAccessible(true);
    String value = (String) stringField.get(null);
    return value;
}
 
Example 38
Project: dubbox-hystrix   File: JavaSerializer.java   View source code 5 votes vote down vote up
public void writeInstance(Object obj, AbstractHessianOutput out)
  throws IOException
{
  for (int i = 0; i < _fields.length; i++) {
    Field field = _fields[i];

    _fieldSerializers[i].serialize(out, obj, field);
  }
}
 
Example 39
Project: jpl-framework   File: InputControlTest.java   View source code 5 votes vote down vote up
/**
 * Resets the command history of the {@link SystemStatus}.
 * 
 * @throws NoSuchFieldException if the use of reflection fails
 * @throws SecurityException if the use of reflection fails
 * @throws IllegalArgumentException if the use of reflection fails
 * @throws IllegalAccessException if the use of reflection fails
 */
private void resetCommandHistoryOfSystemStatus()
      throws NoSuchFieldException,
         SecurityException,
         IllegalArgumentException,
         IllegalAccessException {
   Field f = systemStatus.getClass().getDeclaredField(FIELD_SYSTEM_STATUS_COMMAND_HISTORY);
   f.setAccessible(true);

   @SuppressWarnings("unchecked")
   List<Pair<ICommand, CommandResult>> commandHistory = (List<Pair<ICommand, CommandResult>>) f.get(systemStatus);
   commandHistory.clear();
}
 
Example 40
Project: com.zsmartsystems.zigbee   File: AshFrameHandlerTest.java   View source code 5 votes vote down vote up
private int[] getPacket(int[] data) {
    AshFrameHandler frameHandler = new AshFrameHandler(null);
    byte[] bytedata = new byte[data.length];
    int cnt = 0;
    for (int value : data) {
        bytedata[cnt++] = (byte) value;
    }
    ByteArrayInputStream stream = new ByteArrayInputStream(bytedata);
    ZigBeePort port = new TestPort(stream, null);

    Method privateMethod;
    try {
        Field field = frameHandler.getClass().getDeclaredField("port");
        field.setAccessible(true);
        field.set(frameHandler, port);

        privateMethod = AshFrameHandler.class.getDeclaredMethod("getPacket");
        privateMethod.setAccessible(true);

        return (int[]) privateMethod.invoke(frameHandler);
    } catch (NoSuchMethodException | SecurityException | IllegalArgumentException | IllegalAccessException
            | InvocationTargetException | NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}