Java 类java.lang.reflect.Field 实例源码

项目:GitHub    文件:AndroidNClassLoader.java   
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;
}
项目:HTAPBench    文件:Procedure.java   
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);
}
项目:randomito-all    文件:AnnotationPostProcessorScanner.java   
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);
}
项目:openjdk-jdk10    文件:LIRIntrospection.java   
@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);
    }
}
项目:AlphaLibary    文件:ReflectionHelper.java   
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()]);
}
项目:atlas    文件:RemoteActivityManager.java   
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;
}
项目:Shuriken    文件:ClassWrapper.java   
/**
 * 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)));
}
项目:olingo-jpa    文件:JpaOlingoEntity.java   
@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;
}
项目:otter-G    文件:PipelineParameter.java   
/**
 * 合并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
    }
}
项目:YuiHatano    文件:ShadowResources.java   
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;
}
项目:hibernateMaster    文件:DomainUtil.java   
/**
 * 获取实体类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);
}
项目:nixmash-blog    文件:SiteOptions.java   
@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));
            }
        }
    }
}
项目:xbot_head    文件:ROSBridgeWebSocketClient.java   
@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();
    }
}
项目:solo-spring    文件:Reflections.java   
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;
}
项目:athena    文件:TestUtils.java   
/**
 * 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);
    }
}
项目:febit    文件:ArangoUtil.java   
@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);
}
项目:serviceconnector    文件:ServiceConnector.java   
/**
 * 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");
            }
        }
    }
}
项目:BestPracticeApp    文件:PointView.java   
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;
}
项目:jdk8u-jdk    文件:AWTEvent.java   
/**
 * 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;
}
项目:B4zV4lidator    文件:B4zV4lidatorUtil.java   
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;
}
项目:businessworks    文件:Errors.java   
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());
  }
}
项目:s-store    文件:TestDesignerHints.java   
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
    }
项目:classchecks    文件:SelfServletContextListener.java   
/**
 * 卸载已经装载的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();
    }
}
项目:dremio-oss    文件:TestAccelerationFailures.java   
@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());
}
项目:jarling    文件:AddressesDeserializer.java   
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();
        }
    }
项目:stock-api-sdk    文件:SearchParametersTest.java   
@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));
}
项目:lambda-monitoring    文件:MetricsFinder.java   
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;
    }
项目:stock-api-sdk    文件:LicensePurchaseDetailsTest.java   
@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));
}
项目:TYT    文件:HomeFragment.java   
/**
 * 通过文件名获取资源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;
    }
}
项目:monarch    文件:KerberosUtils.java   
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);
}
项目:qpp-conversion-tool    文件:PathCorrelatorTest.java   
@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);
}
项目:ditb    文件:TestFSHLog.java   
@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();
  }
}
项目:stock-api-sdk    文件:SearchParametersTest.java   
@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());
}
项目:stock-api-sdk    文件:LicenseThumbnailTest.java   
@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));
}
项目:zeratul    文件:ReflectionUtils.java   
/**
 * 获取属性值
 * @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));
}
项目:spring-data-generator    文件:RepositoryStructure.java   
@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;
    }
}
项目:android-dev-challenge    文件:TestUtilities.java   
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;
}
项目:dubbox-hystrix    文件:JavaSerializer.java   
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);
  }
}
项目:jpl-framework    文件:InputControlTest.java   
/**
 * 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();
}
项目:com.zsmartsystems.zigbee    文件:AshFrameHandlerTest.java   
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;
}