java.lang.reflect.Field#set ( )源码实例Demo

下面列出了java.lang.reflect.Field#set ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: flume-ng-kafka-sink   文件: KafkaSinkTest.java
@SuppressWarnings("unchecked")
@Before
public void setup() throws Exception {
	mockProducer = mock(Producer.class);
	mockChannel = mock(Channel.class);
	mockEvent = mock(Event.class);
	mockTx = mock(Transaction.class);
	mockKafkaSink = new KafkaSink();
	
	Field field = AbstractSink.class.getDeclaredField("channel");
	field.setAccessible(true);
	field.set(mockKafkaSink, mockChannel);

	field = KafkaSink.class.getDeclaredField("topic");
	field.setAccessible(true);
	field.set(mockKafkaSink, "test");

	field = KafkaSink.class.getDeclaredField("producer");
	field.setAccessible(true);
	field.set(mockKafkaSink, mockProducer);
	
	when(mockChannel.take()).thenReturn(mockEvent);
	when(mockChannel.getTransaction()).thenReturn(mockTx);
}
 
源代码2 项目: rocketmq-4.3.0   文件: SendMsgStatusCommandTest.java
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
    mQClientAPIImpl = mock(MQClientAPIImpl.class);
    defaultMQAdminExt = new DefaultMQAdminExt();
    defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);

    Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
    field.setAccessible(true);
    field.set(defaultMQAdminExtImpl, mqClientInstance);
    field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
    field.setAccessible(true);
    field.set(mqClientInstance, mQClientAPIImpl);
    field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
    field.setAccessible(true);
    field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
}
 
源代码3 项目: sumk   文件: RpcActionNode.java
public Object invokeByOrder(String... args) throws Throwable {
	if (this.isEmptyArgument()) {
		return this.execute(this.getEmptyArgObj());
	}
	if (args == null) {
		SumkException.throwException(12012, method.getName() + "的参数不能为空");
	}
	if (args.length != argNames.length) {
		Logs.rpc().debug(method.getName() + "需要传递" + argNames.length + "个参数,实际传递" + args.length + "个");
	}

	ArgPojo pojo = Loader.newInstance(this.argClz);
	for (int i = 0; i < fields.length; i++) {
		if (i >= args.length || args[i] == null) {
			continue;
		}
		Field f = fields[i];
		f.set(pojo, RpcGson.fromJson(args[i], f.getGenericType()));
	}
	return this.execute(pojo);
}
 
源代码4 项目: cloudstack   文件: QuotaTariffListCmdTest.java
@Test
public void testQuotaTariffListCmd() throws NoSuchFieldException, IllegalAccessException {
    QuotaTariffListCmd cmd = new QuotaTariffListCmd();

    Field rbField = QuotaTariffListCmd.class.getDeclaredField("_responseBuilder");
    rbField.setAccessible(true);
    rbField.set(cmd, responseBuilder);

    List<QuotaTariffVO> quotaTariffVOList = new ArrayList<QuotaTariffVO>();
    QuotaTariffVO tariff = new QuotaTariffVO();
    tariff.setEffectiveOn(new Date());
    tariff.setCurrencyValue(new BigDecimal(100));
    tariff.setUsageType(QuotaTypes.MEMORY);

    quotaTariffVOList.add(new QuotaTariffVO());
    Mockito.when(responseBuilder.listQuotaTariffPlans(Mockito.eq(cmd))).thenReturn(quotaTariffVOList);
    Mockito.when(responseBuilder.createQuotaTariffResponse(Mockito.any(QuotaTariffVO.class))).thenReturn(new QuotaTariffResponse());

    cmd.execute();
    Mockito.verify(responseBuilder, Mockito.times(1)).createQuotaTariffResponse(Mockito.any(QuotaTariffVO.class));
}
 
/**
 * Tests refreshing access token.
 * @throws Exception in case of errors
 */
public void testRefreshToken() throws Exception {
	// access Keycloak
    assertEquals(5, identityService.createUserQuery().count());

    // expire current token (the dirty way)
    KeycloakIdentityProviderFactory sessionFacory = (KeycloakIdentityProviderFactory) 
    		((ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration()).getIdentityProviderSessionFactory();
    KeycloakContextProvider keycloakContextProvider = getProtectedField(sessionFacory, "keycloakContextProvider");
    KeycloakContext ctx = getProtectedField(keycloakContextProvider, "context");
    Field expiresField = KeycloakContext.class.getDeclaredField("expiresAt");
    expiresField.setAccessible(true);
    expiresField.set(ctx, 0);
    assertTrue(ctx.needsRefresh());
    
	// access Keycloak again
    assertEquals(5, identityService.createUserQuery().count());
    
}
 
源代码6 项目: jdk8u-jdk   文件: ImageIcon.java
public Component run() {
    try {
        final Component component = createNoPermsComponent();

        // 6482575 - clear the appContext field so as not to leak it
        Field appContextField =

                Component.class.getDeclaredField("appContext");
        appContextField.setAccessible(true);
        appContextField.set(component, null);

        return component;
    } catch (Throwable e) {
        // We don't care about component.
        // So don't prevent class initialisation.
        e.printStackTrace();
        return null;
    }
}
 
源代码7 项目: pmq   文件: MqQueueExcutorServiceTest.java
@Test
public void testSendFailMailfailBeginTime50()
		throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
	MockMqClientBase mockMqClientBase = new MockMqClientBase();
	ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
	consumerQueueDto.setPullBatchSize(20);
	MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
			consumerQueueDto);
	Field field = mqQueueExcutorService.getClass().getDeclaredField("failBeginTime");
	field.setAccessible(true);
	field.set(mqQueueExcutorService, System.currentTimeMillis() - 1);
	mqQueueExcutorService.sendFailMail();

	assertEquals("testSendFailMailfailBeginTime50 error", 0,
			((MqQueueResource) mockMqClientBase.getContext().getMqResource()).getSendMailFlag());
}
 
源代码8 项目: onos   文件: JsonDataModelInjector.java
/**
 * Injects text data model on the filed of work-let.
 *
 * @param worklet work-let
 * @param context workflow context
 * @param field   the field of work-let
 * @param model   text data model for the field
 * @throws WorkflowException workflow exception
 */
private static void injectText(Worklet worklet, WorkflowContext context, Field field, JsonDataModel model)
        throws WorkflowException {

    String text = ((JsonDataModelTree) context.data()).textAt(model.path());
    if (Objects.isNull(text)) {
        if (model.optional()) {
            return;
        }
        throw new WorkflowException("Invalid text data model on (" + model.path() + ")");
    }

    if (!(Objects.equals(field.getType(), String.class))) {
        throw new WorkflowException("Target field (" + field + ") is not String");
    }

    try {
        field.setAccessible(true);
        field.set(worklet, text);
    } catch (IllegalAccessException e) {
        throw new WorkflowException(e);
    }
}
 
源代码9 项目: dekorate   文件: WithPod.java
/**
 * Inject a {@link Pod} to the specified {@link Field}.
 * The pod is matched using its corresponding endpoints.
 * In other words this acts like `inject pod of service`
 * @param context      The execution context.
 * @param testInstance The target test instance.
 * @param field        The field to inject.
 */
default void injectPod(ExtensionContext context, Object testInstance, Field field) {
  if (!field.getType().isAssignableFrom(Pod.class)) {
    return;
  }

  //This is to make sure we don't write on fields by accident.
  //Note: we don't require the exact annotation. Any annotation named Inject will do (be it javax, guice etc)
  if (!stream(field.getDeclaredAnnotations()).filter(a -> a.annotationType().getSimpleName().equalsIgnoreCase("Inject")).findAny().isPresent()) {
    return;
  }

  String name = namedAnnotation(field).orElseGet(() -> getName());
  field.setAccessible(true);
  try {
    field.set(testInstance, podForName(context, name));
  } catch (IllegalAccessException e) {
    throw DekorateException.launderThrowable(e);
  }
}
 
源代码10 项目: logging-log4j2   文件: AbstractLogger.java
private void readObject (final ObjectInputStream s) throws ClassNotFoundException, IOException {
    s.defaultReadObject( );
    try {
        Field f = this.getClass().getDeclaredField("logBuilder");
        f.setAccessible(true);
        f.set(this, new LocalLogBuilder(this));
    } catch (NoSuchFieldException | IllegalAccessException ex) {
        StatusLogger.getLogger().warn("Unable to initialize LogBuilder");
    }
}
 
源代码11 项目: cloudstack   文件: VolumeApiServiceImplTest.java
@Test
public void testDetachVolumeFromStoppedXenVm() throws NoSuchFieldException, IllegalAccessException {
    thrown.expect(NullPointerException.class);
    Field dedicateIdField = _detachCmdClass.getDeclaredField("id");
    dedicateIdField.setAccessible(true);
    dedicateIdField.set(detachCmd, 2L);
    volumeApiServiceImpl.detachVolumeFromVM(detachCmd);
}
 
private void injectHostname(Socket socket, String host) {
  try {
    Field field = InetAddress.class.getDeclaredField("hostName");
    field.setAccessible(true);
    field.set(socket.getInetAddress(), host);
  } catch (Exception ignored) {
  }
}
 
源代码13 项目: netbeans   文件: JavaActionProviderTestSupport.java
public static boolean setUserPropertiesPolicy(
        @NonNull JavaActionProvider jap,
        @NullAllowed ActionProviderSupport.UserPropertiesPolicy policy) {
    try {
        final Field f = JavaActionProvider.class.getDeclaredField("userPropertiesPolicy");
        f.setAccessible(true);
        f.set(jap, policy);
        return true;
    } catch (ReflectiveOperationException e) {
        return false;
    }
}
 
源代码14 项目: seezoon-framework-all   文件: CrudService.java
public int save(T t) {
	t.setCreateDate(new Date());
	t.setUpdateDate(t.getCreateDate());
	if (StringUtils.isEmpty(t.getCreateBy())) {
		t.setCreateBy(this.getOperatorUserId());
	}
	t.setUpdateBy(t.getCreateBy());
	//自增主键的insert sql 不能出现插入id 
	if (null == t.getId() || StringUtils.isEmpty(t.getId().toString())) {
		Class<?> clazz = t.getClass();  
	    Type type = clazz.getGenericSuperclass();  
	    ParameterizedType parameterizedType = (ParameterizedType) type;  
	    if (parameterizedType.getActualTypeArguments()[0].equals(String.class)) {
	    		//t.setId(IdGen.uuid()); 这个要是编译可以过去就不用这么麻烦去获取主键类型
	    		Field findField = ReflectionUtils.findField(clazz, "id");
	    		try {
	    			    findField.setAccessible(true);
					findField.set(t, IdGen.uuid());
			} catch (Exception e) {
				logger.error("set id error:",e);
			} 
	    }
	}
	
	int cnt = d.insert(t);
	if (t.isNeedBak()) {
		this.saveBak(t.getId());
	}
	return cnt;
}
 
源代码15 项目: radon   文件: VirtSet.java
@Override
public void handle(VM vm, Object[] operands) throws Exception {
    String ownerName = (String) operands[0];
    String name = (String) operands[1];
    String typeName = (String) operands[2];

    Class clazz = VM.getClazz(ownerName);
    Class type = VM.getClazz(typeName);
    Field field = VM.getField(clazz, name, type);

    if (field == null)
        throw new VMException();

    JWrapper value = vm.pop();

    if (value instanceof JTop)
        value = vm.pop();

    Object ref = vm.pop().asObj();

    if ("int".equals(ownerName))
        field.setInt(ref, value.asInt());
    else if ("long".equals(ownerName))
        field.setLong(ref, value.asLong());
    else if ("float".equals(ownerName))
        field.setFloat(ref, value.asFloat());
    else if ("double".equals(ownerName))
        field.setDouble(ref, value.asDouble());
    else if ("byte".equals(ownerName))
        field.setByte(ref, value.asByte());
    else if ("short".equals(ownerName))
        field.setShort(ref, value.asShort());
    else if ("char".equals(ownerName))
        field.setChar(ref, value.asChar());
    else if ("boolean".equals(ownerName))
        field.setBoolean(ref, value.asBool());
    else
        field.set(ref, value.asObj());
}
 
源代码16 项目: AnnihilationPro   文件: ReflectionUtil.java
public static void setSuperValue(Object instance, String fieldName,
		Object value) throws Exception
{
	Field field = instance.getClass().getSuperclass()
			.getDeclaredField(fieldName);
	field.setAccessible(true);
	field.set(instance, value);
}
 
源代码17 项目: cloudstack   文件: QuotaResponseBuilderImplTest.java
@Before
public void setup() throws IllegalAccessException, NoSuchFieldException {
    // Dummy transaction stack setup
    TransactionLegacy.open("QuotaResponseBuilderImplTest");

    Field tariffDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaTariffDao");
    tariffDaoField.setAccessible(true);
    tariffDaoField.set(quotaResponseBuilder, quotaTariffDao);

    Field balanceDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaBalanceDao");
    balanceDaoField.setAccessible(true);
    balanceDaoField.set(quotaResponseBuilder, quotaBalanceDao);

    Field quotaCreditsDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaCreditsDao");
    quotaCreditsDaoField.setAccessible(true);
    quotaCreditsDaoField.set(quotaResponseBuilder, quotaCreditsDao);

    Field quotaEmailTemplateDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaEmailTemplateDao");
    quotaEmailTemplateDaoField.setAccessible(true);
    quotaEmailTemplateDaoField.set(quotaResponseBuilder, quotaEmailTemplateDao);

    Field userDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_userDao");
    userDaoField.setAccessible(true);
    userDaoField.set(quotaResponseBuilder, userDao);

    Field quotaServiceField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaService");
    quotaServiceField.setAccessible(true);
    quotaServiceField.set(quotaResponseBuilder, quotaService);

    Field accountDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_accountDao");
    accountDaoField.setAccessible(true);
    accountDaoField.set(quotaResponseBuilder, accountDao);

    Field regionMgrField = QuotaResponseBuilderImpl.class.getDeclaredField("_accountMgr");
    regionMgrField.setAccessible(true);
    regionMgrField.set(quotaResponseBuilder, accountMgr);
}
 
源代码18 项目: cosmic   文件: CertServiceTest.java
@Test
public void runUploadSslCertExpiredCert() throws IOException, IllegalAccessException, NoSuchFieldException {

    // Reading appropritate files
    final String certFile = URLDecoder.decode(getClass().getResource("/certs/expired_cert.crt").getFile(), Charset.defaultCharset().name());
    final String keyFile = URLDecoder.decode(getClass().getResource("/certs/rsa_self_signed.key").getFile(), Charset.defaultCharset().name());

    final String cert = readFileToString(new File(certFile));
    final String key = readFileToString(new File(keyFile));

    final CertServiceImpl certService = new CertServiceImpl();

    //setting mock objects
    certService._accountMgr = Mockito.mock(AccountManager.class);
    final Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    when(certService._accountMgr.getAccount(anyLong())).thenReturn(account);

    certService._domainDao = Mockito.mock(DomainDao.class);
    final DomainVO domain = new DomainVO("networkdomain", 1L, 1L, "networkdomain");
    when(certService._domainDao.findByIdIncludingRemoved(anyLong())).thenReturn(domain);

    certService._sslCertDao = Mockito.mock(SslCertDao.class);
    when(certService._sslCertDao.persist(any(SslCertVO.class))).thenReturn(new SslCertVO());

    //creating the command
    final UploadSslCertCmd uploadCmd = new UploadSslCertCmdExtn();
    final Class<?> _class = uploadCmd.getClass().getSuperclass();

    final Field certField = _class.getDeclaredField("cert");
    certField.setAccessible(true);
    certField.set(uploadCmd, cert);

    final Field keyField = _class.getDeclaredField("key");
    keyField.setAccessible(true);
    keyField.set(uploadCmd, key);

    try {
        certService.uploadSslCert(uploadCmd);
        fail("Given an expired certificate, upload should fail");
    } catch (final Exception e) {
        assertTrue(e.getMessage().contains("Certificate expired"));
    }
}
 
源代码19 项目: netbeans   文件: CountingSecurityManager.java
private boolean acceptFileWrite(String file) {
    String ud = System.getProperty("netbeans.user");
    if (ud == null) {
        // still initializing
        return false;
    }
    if (!startsWith(file, ud)) {
        return false;
    }

    String f = file.substring(ud.length()).replace(File.separatorChar, '/');
    if (f.startsWith("/.metadata")) {
        // equinox runtime
        return false;
    }
    if (f.contains("config/Modules")) {
        return false;
    }
    if (f.contains("config/Windows2Local")) {
        return false;
    }
    if (f.contains("var/cache/netigso")) {
        return false;
    }
    if (f.endsWith(".hg")) {
        try {
            Class<?> ref = Class.forName("org.netbeans.modules.versioning.util.Utils", true, Thread.currentThread().getContextClassLoader());
            Field unver = ref.getDeclaredField("unversionedFolders");
            unver.setAccessible(true);
            unver.set(null, new File[]{new File(ud).getParentFile()});
            return false;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    
    if (startsWith(file, ud)) {
        if (startsWith(f, "/")) {
            f = f.substring(1);
        }
        if (allowed.contains(f)) {
            return false;
        }
    }
    for (StackTraceElement e : Thread.currentThread().getStackTrace()) {
        if (e.getClassName().contains("junit.JUnitTestRunner")) {
            return false;
        }
        // this happens from time to time (according to GC being scheduled or not)
        // and shall not influence the results of this test
        if (e.getClassName().equals("org.openide.util.WeakListenerImpl$ListenerReference") && e.getMethodName().equals("getRemoveMethod")) {
            return false;
        }
    }

    return prefix == null || startsWith(file, prefix);
}
 
源代码20 项目: skywalking   文件: FieldSetter.java
public static <T> void setValue(Object instance, String fieldName,
    T value) throws IllegalAccessException, NoSuchFieldException {
    Field field = instance.getClass().getDeclaredField(fieldName);
    field.setAccessible(true);
    field.set(instance, value);
}