Java Code Examples for java.lang.reflect.Field.getType()

The following are Jave code examples for showing how to use getType() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: buildAPKsSamples   File: Injector.java   View Source Code Vote up 7 votes
/**
 * Injects all fields that are marked with the {@link InjectView} annotation.
 * <p>
 * For each field marked with the InjectView annotation, a call to
 * {@link Activity#findViewById(int)} will be made, passing in the resource id stored in the
 * value() method of the InjectView annotation as the int parameter, and the result of this call
 * will be assigned to the field.
 *
 * @throws IllegalStateException if injection fails, common causes being that you have used an
 *             invalid id value, or you haven't called setContentView() on your Activity.
 */
public void inject() {
    for (Field field : mActivity.getClass().getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
            if (annotation.annotationType().equals(InjectView.class)) {
                try {
                    Class<?> fieldType = field.getType();
                    int idValue = InjectView.class.cast(annotation).value();
                    field.setAccessible(true);
                    Object injectedValue = fieldType.cast(mActivity.findViewById(idValue));
                    if (injectedValue == null) {
                        throw new IllegalStateException("findViewById(" + idValue
                                + ") gave null for " +
                                field + ", can't inject");
                    }
                    field.set(mActivity, injectedValue);
                    field.setAccessible(false);
                } catch (IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        }
    }
}
 
Example 2
Project: heapunit   File: SimpleHeapImage.java   View Source Code Vote up 6 votes
private void setPrimitive(Object o, Field f, String value) throws IllegalArgumentException, IllegalAccessException {
    if (f.getType() == boolean.class) {
        f.set(o, Boolean.valueOf(value));
    }
    else if (f.getType() == byte.class) {
        f.set(o, Byte.valueOf(value));
    }
    else if (f.getType() == char.class) {
        f.set(o, value.charAt(0));
    }
    else if (f.getType() == short.class) {
        f.set(o, Short.valueOf(value));
    }
    else if (f.getType() == int.class) {
        f.set(o, Integer.valueOf(value));
    }
    else if (f.getType() == long.class) {
        f.set(o, Long.valueOf(value));
    }
    else if (f.getType() == float.class) {
        f.set(o, Float.valueOf(value));
    }
    else if (f.getType() == double.class) {
        f.set(o, Double.valueOf(value));
    }
}
 
Example 3
Project: OftenPorter   File: Porter.java   View Source Code Vote up 6 votes
/**
 * 获取正确的变量类型。
 *
 * @return
 */
Class getFieldRealClass(Field field)
{
    Class<?> ftype = field.getType();
    if (field.getGenericType() == null || superGenericClasses == null)
    {
        return ftype;
    }
    for (int i = 0; i < superGenericClasses.length; i++)
    {
        if (WPTool.isAssignable(superGenericClasses[i], ftype))
        {
            return superGenericClasses[i];
        }
    }
    return ftype;
}
 
Example 4
Project: ciguan   File: AsMetaField.java   View Source Code Vote up 6 votes
/**
 * Instantiates a new as meta field.
 *
 * @param pOwner the owner
 * @param pField the field
 */
public AsMetaField(String pOwner, Field pField) {
    owner = pOwner;
    name = pField.getName();
    isArray = pField.getType().getComponentType() != null;
    Class<?> tTypeClass = isArray ? pField.getType().getComponentType() : pField.getType();
    type = As.getTypeName(tTypeClass);
    Class<?> tConstantType = As.getMetaDataHandler().getConstantType(pField);
    if (tConstantType != null) {
        constant = As.getTypeName(tConstantType);
    }
    else if (Enum.class.isAssignableFrom(tTypeClass)) {
        constant = type;
    }
    Class<?> tReferencedType = As.getMetaDataHandler().getReferencedType(pField);
    referencedType = tReferencedType != null ? As.getTypeName(tReferencedType) : null;
    mBusinessType = As.getMetaDataHandler().getBusinessType(pField);
    if (mBusinessType != null) {
        businessType = mBusinessType.name();
    }
    isObject = As.getType(type) != null;
}
 
Example 5
Project: rest.vertx   File: ContextProviderFactory.java   View Source Code Vote up 6 votes
public static void injectContext(Object instance, RouteDefinition definition, RoutingContext routeContext) throws ContextException {

		if (instance == null) {
			return;
		}

		if (hasContext(instance.getClass())) {
			Field[] fields = instance.getClass().getDeclaredFields();
			for (Field field : fields) {
				Annotation found = field.getAnnotation(Context.class);
				if (found != null) {

					Object context = provideContext(definition, field.getType(), null, routeContext);
					try {
						field.setAccessible(true);
						field.set(instance, context);
					}
					catch (IllegalAccessException e) {
						throw new ContextException("Can't provide @Context for: " + field.getType() + " - " + e.getMessage());
					}
				}
			}
		}
	}
 
Example 6
Project: Backmemed   File: ReflectorRaw.java   View Source Code Vote up 6 votes
public static Field getField(Class p_getField_0_, Class p_getField_1_)
{
    try
    {
        Field[] afield = p_getField_0_.getDeclaredFields();

        for (int i = 0; i < afield.length; ++i)
        {
            Field field = afield[i];

            if (field.getType() == p_getField_1_)
            {
                field.setAccessible(true);
                return field;
            }
        }

        return null;
    }
    catch (Exception var5)
    {
        return null;
    }
}
 
Example 7
Project: openjdk-jdk10   File: MemberName.java   View Source Code Vote up 5 votes
@SuppressWarnings("LeakingThisInConstructor")
public MemberName(Field fld, boolean makeSetter) {
    Objects.requireNonNull(fld);
    // fill in vmtarget, vmindex while we have fld in hand:
    MethodHandleNatives.init(this, fld);
    assert(isResolved() && this.clazz != null);
    this.name = fld.getName();
    this.type = fld.getType();
    assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
    byte refKind = this.getReferenceKind();
    assert(refKind == (isStatic() ? REF_getStatic : REF_getField));
    if (makeSetter) {
        changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind);
    }
}
 
Example 8
Project: Climatar   File: ControllerManager.java   View Source Code Vote up 5 votes
private void initializeControllerViews(Controller controller)
		throws InstantiationException, IllegalAccessException {
	Class<? extends Controller> controllerClass = controller.getClass();

	for (Field field : controllerClass.getDeclaredFields()) {
		Class<?> fieldType = field.getType();

		if (View.class.isAssignableFrom(fieldType)) {
			View view = (View) fieldType.newInstance();

			field.setAccessible(true);
			field.set(controller, view);
			field.setAccessible(false);

			// The next line is handled by View#setController()
			// controller.addView(view);

			AllowController annotation = fieldType.getAnnotation(AllowController.class);
			if (annotation != null) {

				boolean valid = false;

				for (Class<? extends Controller> c : annotation.value()) {
					if (c.isInstance(controller)) {
						view.setController(controller);
						view.initializeView();
						valid = true;
					}
				}

				if (!valid) {
					throw new RuntimeException(
							fieldType.getSimpleName() + " is not allowed in " + controllerClass.getSimpleName());
				}
			}
		}
	}
}
 
Example 9
Project: oscm   File: SubscriptionServiceMockBase.java   View Source Code Vote up 5 votes
private static void mockMember(Object member, Object mock, Field f)
        throws IllegalAccessException {
    Class<?> t = f.getType();
    if (t.isInstance(mock)) {
        f.setAccessible(true);
        f.set(member, mock);
    }
}
 
Example 10
Project: guava-mock   File: HttpHeadersTest.java   View Source Code Vote up 5 votes
static ImmutableSet<Field> relevantFields(Class<?> cls) {
  ImmutableSet.Builder<Field> builder = ImmutableSet.builder();
  for (Field field : cls.getDeclaredFields()) {
    /*
     * Coverage mode generates synthetic fields.  If we ever add private
     * fields, they will cause similar problems, and we may want to switch
     * this check to isAccessible().
     */
    if (!field.isSynthetic() && field.getType() == String.class) {
      builder.add(field);
    }
  }
  return builder.build();
}
 
Example 11
Project: vscrawler   File: AwkTuples.java   View Source Code Vote up 5 votes
public static String toOpcodeString(int opcode) {
	Class c = AwkTuples.class;
	Field[] fields = c.getDeclaredFields();
	try {
		for (Field field : fields) {
			if ((field.getModifiers() & Modifier.STATIC) > 0 && field.getType() == Integer.TYPE && field.getInt(null) == opcode) {
				return field.getName();
			}
		}
	} catch (IllegalAccessException iac) {
		LOG.error("Failed to create OP-Code string", iac);
		return "[" + opcode + ": " + iac + "]";
	}
	return "{" + opcode + "}";
}
 
Example 12
Project: randomito-all   File: ReflectionUtils.java   View Source Code Vote up 5 votes
/**
 * Sets given value specified by path of provided object.
 * Example:
 * Given path: "address.street"
 * means that on the given object there is a field named "address"
 * that, once referenced, contains field named "street"
 *
 * @param instance - object which contains the field.
 * @param path     - path to be used
 * @param value    - value to be set on the object.
 * @throws NoSuchMethodException     - exception
 * @throws IllegalAccessException    - exception
 * @throws InvocationTargetException - exception
 * @throws InstantiationException    - exception
 */
public static void setPathValue(Object instance, String path, Object value) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    checkNotNull(path);
    Object ref = instance;
    Field refField = null;
    String[] split = path.split("\\.");
    for (int i = 0; i < split.length; i++) {
        String property = split[i];
        refField = getDeclaredField(ref.getClass(), property);
        if (!makeFieldAccessible(refField)) {
            throw new RandomitoException("Path cannot be accessed: " + path);
        }
        if (i < split.length - 1) {
            ref = refField.get(ref);
            if (ref == null) {
                throw new RandomitoException("Property is null: '"
                        + join(subarray(split, 0, i + 1), ".")
                        + "'. Maybe increase 'depth' parameter?");
            }
        }
    }

    if (value == null) {
        refField.set(instance, null);
        return;
    }
    Class<?> type = refField.getType();
    if (type.isPrimitive()) {
        type = ClassUtils.primitiveToWrapper(type);
    }
    if (Number.class.isAssignableFrom(type)) {
        refField.set(ref, stringToNumber(value, type));
    } else {
        refField.set(ref, value);
    }
}
 
Example 13
Project: jspoon   File: HtmlAdapter.java   View Source Code Vote up 5 votes
HtmlAdapter(Jspoon jspoon, Class<T> clazz) {
    this.jspoon = jspoon;
    this.clazz = clazz;
    htmlFieldCache = new LinkedHashMap<>();

    Field[] declaredFields = clazz.getDeclaredFields();
    for (Field field : declaredFields) {
        Class<?> fieldClass = field.getType();

        // Annotated field
        Selector selector = field.getAnnotation(Selector.class);

        // Not annotated field of annotated class
        if (selector == null) {
            selector = fieldClass.getAnnotation(Selector.class);
        }

        // Not annotated field - List of annotated type
        if (selector == null && List.class.isAssignableFrom(fieldClass)) {
            selector = getSelectorFromListType(field);
        }

        if (selector != null) {
            addCachedHtmlField(field, selector, fieldClass);
        }
    }

    if (htmlFieldCache.isEmpty()) {
        throw new EmptySelectorException(clazz);
    }
}
 
Example 14
Project: Backmemed   File: ReflectorRaw.java   View Source Code Vote up 5 votes
public static Field[] getFields(Object p_getFields_0_, Field[] p_getFields_1_, Class p_getFields_2_, Object p_getFields_3_)
{
    try
    {
        List<Field> list = new ArrayList();

        for (int i = 0; i < p_getFields_1_.length; ++i)
        {
            Field field = p_getFields_1_[i];

            if (field.getType() == p_getFields_2_)
            {
                boolean flag = Modifier.isStatic(field.getModifiers());

                if ((p_getFields_0_ != null || flag) && (p_getFields_0_ == null || !flag))
                {
                    field.setAccessible(true);
                    Object object = field.get(p_getFields_0_);

                    if (object == p_getFields_3_)
                    {
                        list.add(field);
                    }
                    else if (object != null && p_getFields_3_ != null && object.equals(p_getFields_3_))
                    {
                        list.add(field);
                    }
                }
            }
        }

        Field[] afield = (Field[])((Field[])list.toArray(new Field[list.size()]));
        return afield;
    }
    catch (Exception var9)
    {
        return null;
    }
}
 
Example 15
Project: googles-monorepo-demo   File: HttpHeadersTest.java   View Source Code Vote up 5 votes
static ImmutableSet<Field> relevantFields(Class<?> cls) {
  ImmutableSet.Builder<Field> builder = ImmutableSet.builder();
  for (Field field : cls.getDeclaredFields()) {
    /*
     * Coverage mode generates synthetic fields.  If we ever add private
     * fields, they will cause similar problems, and we may want to switch
     * this check to isAccessible().
     */
    if (!field.isSynthetic() && field.getType() == String.class) {
      builder.add(field);
    }
  }
  return builder.build();
}
 
Example 16
Project: openjdk-jdk10   File: ObjectStreamField.java   View Source Code Vote up 4 votes
ObjectStreamField(Field field) {
    this(field.getName(), field.getType());
    this.field = field;
}
 
Example 17
Project: openjdk-jdk10   File: AtomicReferenceFieldUpdater.java   View Source Code Vote up 4 votes
AtomicReferenceFieldUpdaterImpl(final Class<T> tclass,
                                final Class<V> vclass,
                                final String fieldName,
                                final Class<?> caller) {
    final Field field;
    final Class<?> fieldClass;
    final int modifiers;
    try {
        field = AccessController.doPrivileged(
            new PrivilegedExceptionAction<Field>() {
                public Field run() throws NoSuchFieldException {
                    return tclass.getDeclaredField(fieldName);
                }
            });
        modifiers = field.getModifiers();
        sun.reflect.misc.ReflectUtil.ensureMemberAccess(
            caller, tclass, null, modifiers);
        ClassLoader cl = tclass.getClassLoader();
        ClassLoader ccl = caller.getClassLoader();
        if ((ccl != null) && (ccl != cl) &&
            ((cl == null) || !isAncestor(cl, ccl))) {
            sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
        }
        fieldClass = field.getType();
    } catch (PrivilegedActionException pae) {
        throw new RuntimeException(pae.getException());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    if (vclass != fieldClass)
        throw new ClassCastException();
    if (vclass.isPrimitive())
        throw new IllegalArgumentException("Must be reference type");

    if (!Modifier.isVolatile(modifiers))
        throw new IllegalArgumentException("Must be volatile type");

    // Access to protected field members is restricted to receivers only
    // of the accessing class, or one of its subclasses, and the
    // accessing class must in turn be a subclass (or package sibling)
    // of the protected member's defining class.
    // If the updater refers to a protected field of a declaring class
    // outside the current package, the receiver argument will be
    // narrowed to the type of the accessing class.
    this.cclass = (Modifier.isProtected(modifiers) &&
                   tclass.isAssignableFrom(caller) &&
                   !isSamePackage(tclass, caller))
                  ? caller : tclass;
    this.tclass = tclass;
    this.vclass = vclass;
    this.offset = U.objectFieldOffset(field);
}
 
Example 18
Project: Equella   File: BasicPropertySerialiser.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
@Override
public void load(Object object, Field field, Property property, Map<String, String> properties)
	throws IllegalAccessException, MalformedURLException
{
	Class type = field.getType();
	String key = property.key();
	String value = properties.get(key);

	if( value != null )
	{
		if( String.class.isAssignableFrom(type) )
		{
			field.set(object, value);
		}
		else if( Integer.TYPE.isAssignableFrom(type) )
		{
			field.setInt(object, Integer.parseInt(value));
		}
		else if( Boolean.TYPE.isAssignableFrom(type) )
		{
			field.setBoolean(object, Boolean.parseBoolean(value));
		}
		else if( Long.TYPE.isAssignableFrom(type) )
		{
			field.setLong(object, Long.parseLong(value));
		}
		else if( URL.class.isAssignableFrom(type) )
		{
			field.set(object, new URL(value));
		}
		else if( Enum.class.isAssignableFrom(type) )
		{
			try
			{
				field.set(object, Enum.valueOf(type, value));
			}
			catch( IllegalArgumentException iae )
			{
				// Ignore if value does not match enum - do not set field
			}
		}
	}
}
 
Example 19
Project: OpenJSharp   File: FieldGetter.java   View Source Code Vote up 4 votes
public FieldGetter(Field f) {
    field = f;
    type = f.getType();
}
 
Example 20
Project: openjdk-jdk10   File: ObjectStreamField.java   View Source Code Vote up 4 votes
ObjectStreamField(Field field) {
    this(field.getName(), field.getType());
    setField( field ) ;
}