setAccessible ( )源码实例Demo

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

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

源代码1 项目: BedwarsRel   文件: VillagerItemShop.java
private EntityVillager createVillager() {
  try {
    EntityVillager ev =
        new EntityVillager(((CraftWorld) this.game.getRegion().getWorld()).getHandle());
    Field careerField = EntityVillager.class.getDeclaredField("by");
    careerField.setAccessible(true);
    careerField.set(ev, Integer.valueOf(10));

    return ev;
  } catch (Exception e) {
    BedwarsRel.getInstance().getBugsnag().notify(e);
    e.printStackTrace();
  }

  return null;
}
 
源代码2 项目: rocketmq-read   文件: MixAll.java
/**
 * 对象变成properties
 * @param object ;
 * @return ;
 */
public static Properties object2Properties(final Object object) {
    Properties properties = new Properties();

    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String name = field.getName();
            if (!name.startsWith("this")) {
                Object value = null;
                try {
                    field.setAccessible(true);
                    value = field.get(object);
                } catch (IllegalAccessException e) {
                    log.error("Failed to handle properties", e);
                }

                if (value != null) {
                    properties.setProperty(name, value.toString());
                }
            }
        }
    }

    return properties;
}
 
源代码3 项目: onos   文件: JsonDataModelInjector.java
/**
 * Injects json object node 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   json object node data model for the field
 * @throws WorkflowException workflow exception
 */
private static void injectObjectNode(Worklet worklet, WorkflowContext context, Field field, JsonDataModel model)
        throws WorkflowException {

    ObjectNode objNode = ((JsonDataModelTree) context.data()).objectAt(model.path());
    if (Objects.isNull(objNode)) {
        if (model.optional()) {
            return;
        }
        throw new WorkflowException("Invalid object node data model on (" + model.path() + ")");
    }

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

    try {
        field.setAccessible(true);
        field.set(worklet, objNode);
    } catch (IllegalAccessException e) {
        throw new WorkflowException(e);
    }
}
 
源代码4 项目: mykit-db-sync   文件: BaseBuilder.java
/**
 * 解析e中的元素,将数据填充到o中
 * @param e 解析的XML Element对象
 * @param o 存放解析后的XML Element对象
 * @return 存放有解析后数据的Object
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
protected Object elementInObject(Element e, Object o) throws IllegalArgumentException, IllegalAccessException {
    Class<?> clazz = o.getClass();
    while (clazz != null){
        Field[] fields = clazz.getDeclaredFields();
        for (int index = 0; index < fields.length; index++) {
            Field item = fields[index];
            //当前字段不是serialVersionUID,同时当前字段不包含serialVersionUID
            if (!MykitDbSyncConstants.FIELD_SERIALVERSIONUID.equals(item.getName()) && !item.getName().contains(MykitDbSyncConstants.FIELD_SERIALVERSIONUID)){
                item.setAccessible(true);
                item.set(o, e.element(item.getName()).getTextTrim());
            }
        }
        clazz = clazz.getSuperclass();
    }
    return o;
}
 
源代码5 项目: albedo   文件: ExcelUtil.java
/**
 * 填充excel数据
 *
 * @param index 序号
 * @param row   单元格行
 */
public void fillExcelData(int index, Row row) {
	int startNo = index * SHEET_SIZE;
	int endNo = Math.min(startNo + SHEET_SIZE, list.size());
	for (int i = startNo; i < endNo; i++) {
		row = sheet.createRow(i + 1 - startNo);
		// 得到导出对象.
		T vo = list.get(i);
		int column = 0;
		for (Object[] os : fields) {
			Field field = (Field) os[0];
			ExcelField excelField = (ExcelField) os[1];
			// 设置实体类私有属性可访问
			field.setAccessible(true);
			this.addCell(excelField, row, vo, field, column++);
		}
	}
}
 
@Test
public void getCreatesSenderWithCorrectDatabaseName() throws Exception {
    final MetricsInfluxDbReporterConfiguration configuration = new MetricsInfluxDbReporterConfiguration() {
        @Override
        public URI getUri() {
            return URI.create("udp://127.0.0.1:8086/data_base_1");
        }
    };
    final InfluxDbSenderProvider provider = new InfluxDbSenderProvider(configuration);
    final InfluxDbSender influxDbSender = provider.get();

    final Field field = Class.forName("com.izettle.metrics.influxdb.InfluxDbBaseSender").getDeclaredField("influxDbWriteObject");
    field.setAccessible(true);
    final InfluxDbWriteObject influxDbWriteObject = (InfluxDbWriteObject) field.get(influxDbSender);
    assertEquals("data_base_1", influxDbWriteObject.getDatabase());
}
 
@Test
public void testLineMessagingClientBuilder() throws Exception {
    // Do
    final LineMessagingClientBuilder defaultBuilder = new LineMessagingClientBuilder();
    final Field field = defaultBuilder.getClass().getDeclaredField("apiEndPoint");
    field.setAccessible(true);
    final Object apiEndPoint = field.get(defaultBuilder);

    // Verify
    assertThat(apiEndPoint)
            .isEqualTo(URI.create("https://api.line.me/"));
}
 
/**
 * 根据主键id更新一条数据,支持局部更新,id非空<br/>
 * eliminate:是否剔除NULL值属性
 *
 * @param t
 * @return
 * @throws SystemException
 */
public synchronized Boolean execute(T t, Boolean eliminate) throws SystemException {
    try {
        if (eliminate) {
            return this.execute(t);
        }
        UpdateESObject obj = this.setConfig(this.getConfig(), UpdateESObject.class.newInstance());
        Field f = t.getClass().getDeclaredField(primaryKeyName);
        f.setAccessible(true);
        obj.setId(f.get(t));
        Map<Object, Object> data = ESSearchConvertor.object2Map(t);
        List<Node> nodes = this.getCascade(t);
        if (ListUtils.isNotBlank(nodes)) {
            nodes.forEach(node -> {
                data.put(String.format("_%s", node.getNodeName()), node.getNodeValue());
            });
        }
        obj.setDataMap(data);
        SearchBaseResult<Boolean> result = SearchBeanContext.getBean(ESSearchService.class).esUpdate(obj);
        if (result.isSuccess()) {
            return result.getResult();
        } else {
            throw new SystemException(FrameworkExceptionConstants.ERROR_SEARCH_ENGINES, result.toJSON());
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new SystemException(FrameworkExceptionConstants.ERROR_SEARCH_ENGINES, "搜索引擎异常(根据主键id更新一条数据): t={" + t + "}, error={" + e.getMessage() + "}");
    }
}
 
源代码9 项目: java-gitlab-api   文件: GitlabHTTPRequestor.java
private HttpURLConnection setupConnection(URL url) throws IOException {
    if (root.isIgnoreCertificateErrors()) {
        ignoreCertificateErrors();
    }

    if (apiToken != null && authMethod == AuthMethod.URL_PARAMETER) {
        String urlWithAuth = url.toString();
        urlWithAuth = urlWithAuth + (urlWithAuth.indexOf('?') > 0 ? '&' : '?') +
                tokenType.getTokenParamName() + "=" + apiToken;
        url = new URL(urlWithAuth);
    }

    HttpURLConnection connection = root.getProxy() != null ?
            (HttpURLConnection) url.openConnection(root.getProxy()) : (HttpURLConnection) url.openConnection();
    if (apiToken != null && authMethod == AuthMethod.HEADER) {
        connection.setRequestProperty(tokenType.getTokenHeaderName(),
                String.format(tokenType.getTokenHeaderFormat(), apiToken));
    }

    connection.setReadTimeout(root.getResponseReadTimeout());
    connection.setConnectTimeout(root.getConnectionTimeout());

    try {
        connection.setRequestMethod(method.name());
    } catch (ProtocolException e) {
        // Hack in case the API uses a non-standard HTTP verb
        try {
            Field methodField = connection.getClass().getDeclaredField("method");
            methodField.setAccessible(true);
            methodField.set(connection, method.name());
        } catch (Exception x) {
            throw new IOException("Failed to set the custom verb", x);
        }
    }
    connection.setRequestProperty("User-Agent", root.getUserAgent());
    connection.setRequestProperty("Accept-Encoding", "gzip");
    return connection;
}
 
源代码10 项目: FastAsyncWorldedit   文件: ReflectionUtils.java
public static <T> List<T> getList(List<T> list) {
    try {
        Class<? extends List> clazz = (Class<? extends List>) Class.forName("java.util.Collections$UnmodifiableList");
        if (!clazz.isInstance(list)) return list;
        Field m = clazz.getDeclaredField("list");
        m.setAccessible(true);
        return (List<T>) m.get(list);
    } catch (Throwable e) {
        MainUtil.handleError(e);
        return list;
    }
}
 
源代码11 项目: CoordinatorLayoutExample   文件: StatusBarUtil.java
/**
 * 设置状态栏图标为深色和魅族特定的文字风格
 * 可以用来判断是否为Flyme用户
 * @param window 需要设置的窗口
 * @param dark 是否把状态栏字体及图标颜色设置为深色
 * @return  boolean 成功执行返回true
 *
 */
public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
    boolean result = false;
    if (window != null) {
        try {
            WindowManager.LayoutParams lp = window.getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class
                    .getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (dark) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            window.setAttributes(lp);
            result = true;
        } catch (Exception e) {

        }
    }
    return result;
}
 
源代码12 项目: distributedlog   文件: TestZooKeeperClient.java
@Test(timeout = 60000)
public void testZooKeeperReconnectionBlockingRetryThread() throws Exception {
    int sessionTimeoutMs = 100;
    ZooKeeperClient zkc = clientBuilder(sessionTimeoutMs).zkAclId(null).build();
    ZooKeeper zk = zkc.get();
    assertTrue(zk instanceof org.apache.bookkeeper.zookeeper.ZooKeeperClient);
    org.apache.bookkeeper.zookeeper.ZooKeeperClient bkZkc =
            (org.apache.bookkeeper.zookeeper.ZooKeeperClient) zk;
    // get the connect executor
    Field connectExecutorField = bkZkc.getClass().getDeclaredField("connectExecutor");
    connectExecutorField.setAccessible(true);
    ExecutorService connectExecutor = (ExecutorService) connectExecutorField.get(bkZkc);
    final CountDownLatch latch = new CountDownLatch(1);
    // block retry thread in the zookeeper client
    connectExecutor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
            }
        }
    });
    ZooKeeperClientUtils.expireSession(zkc, zkServers, 2 * sessionTimeoutMs);
    ZooKeeper newZk;
    while ((newZk = zkc.get()) == zk) {
        TimeUnit.MILLISECONDS.sleep(sessionTimeoutMs / 2);
    }
    assertEquals(ZooKeeper.States.CONNECTED, newZk.getState());
}
 
源代码13 项目: influxdb-java   文件: Point.java
/**
 * Adds field map from object by reflection using {@link org.influxdb.annotation.Column}
 * annotation.
 *
 * @param pojo POJO Object with annotation {@link org.influxdb.annotation.Column} on fields
 * @return the Builder instance
 */
public Builder addFieldsFromPOJO(final Object pojo) {

  Class<? extends Object> clazz = pojo.getClass();
  while (clazz != null) {

    for (Field field : clazz.getDeclaredFields()) {

      Column column = field.getAnnotation(Column.class);

      if (column == null) {
        continue;
      }

      field.setAccessible(true);
      String fieldName = column.name();
      addFieldByAttribute(pojo, field, column, fieldName);
    }
  clazz = clazz.getSuperclass();
}

  if (this.fields.isEmpty()) {
    throw new BuilderException("Class " + pojo.getClass().getName()
        + " has no @" + Column.class.getSimpleName() + " annotation");
  }

  return this;
}
 
源代码14 项目: biojava   文件: ScopFactoryTest.java
@Before
public void setUp() throws Exception {
	// reset static values
	Field versionedScopDBs = ScopFactory.class.getDeclaredField("versionedScopDBs");
	versionedScopDBs.setAccessible(true);
	versionedScopDBs.set(null, new HashMap<String, ScopDatabase>());
	Field defaultVersion = ScopFactory.class.getDeclaredField("defaultVersion");
	defaultVersion.setAccessible(true);
	defaultVersion.set(null, ScopFactory.LATEST_VERSION);
}
 
源代码15 项目: aa   文件: UtilUnsafe.java
/** Fetch the Unsafe.  Use With Caution. */
public static Unsafe getUnsafe() {
  // Not on bootclasspath
  if( UtilUnsafe.class.getClassLoader() == null )
    return Unsafe.getUnsafe();
  try {
    final Field fld = Unsafe.class.getDeclaredField("theUnsafe");
    fld.setAccessible(true);
    return (Unsafe) fld.get(UtilUnsafe.class);
  } catch (Exception e) {
    throw new RuntimeException("Could not obtain access to sun.misc.Unsafe", e);
  }
}
 
/**
 * Set IGFS REST handler error flag to the given state.
 *
 * @param flag Flag state.
 * @throws Exception If failed.
 */
private void switchHandlerErrorFlag(boolean flag) throws Exception {
    IgfsProcessorAdapter igfsProc = ((IgniteKernal)grid(0)).context().igfs();

    Map<String, IgfsContext> igfsMap = getField(igfsProc, "igfsCache");

    IgfsServerManager srvMgr = F.first(igfsMap.values()).server();

    Collection<IgfsServer> srvrs = getField(srvMgr, "srvrs");

    IgfsServerHandler igfsHnd = getField(F.first(srvrs), "hnd");

    Field field = igfsHnd.getClass().getDeclaredField("errWrite");

    field.setAccessible(true);

    field.set(null, flag);
}
 
源代码17 项目: scheduling   文件: JavaExecutable.java
/**
 * Initialization default method for a java task.<br>
 * <p>
 * By default, this method does automatic assignment between the value given in the arguments map
 * and the fields contained in your executable.<br>
 * If the field type and the argument type are different and if the argument type is String
 * (i.e. for all jobs defined with XML descriptors), then a automatic mapping is tried.
 * Managed types are byte, short, int, long, boolean and the corresponding classes, other type
 * must be handle by user by overriding this method.<br><br>
 * For example, if you set as argument the key="var", value="12" in the XML descriptor<br>
 * just add an int (or Integer, long, Long) field named "var" in your executable.
 * The default {@link #init(java.util.Map)} method will store your arguments into the integer class field.
 * </p>
 * To avoid this default behavior, just override this method to make your own initialization.
 *
 * @param args a map containing the different parameter names and values given by the user task.
 */
public void init(Map<String, Serializable> args) throws Exception {
    if (args == null) {
        return;
    }
    Class<?> current = this.getClass();
    while (JavaExecutable.class.isAssignableFrom(current)) {
        for (Entry<String, Serializable> e : args.entrySet()) {
            try {
                Field f = current.getDeclaredField(e.getKey());
                // if f does not exist -> catch block
                f.setAccessible(true);
                Class<?> fieldClass = f.getType();
                Class<?> valueClass = e.getValue().getClass();
                // unbox manually as it is not done automatically
                // ie : int is not assignable from Integer
                if (valueClass.equals(Integer.class) || valueClass.equals(Short.class) ||
                    valueClass.equals(Long.class) || valueClass.equals(Byte.class) ||
                    valueClass.equals(Boolean.class)) {
                    e.setValue(e.getValue().toString());
                    valueClass = String.class;
                }
                if (String.class.equals(valueClass) && !String.class.equals(fieldClass)) {
                    String valueAsString = (String) e.getValue();
                    // parameter has been defined as string in XML
                    // try to convert it automatically
                    if (fieldClass.equals(Integer.class) || fieldClass.equals(int.class)) {
                        f.set(this, Integer.parseInt(valueAsString));
                    } else if (fieldClass.equals(Short.class) || fieldClass.equals(short.class)) {
                        f.set(this, Short.parseShort(valueAsString));
                    } else if (fieldClass.equals(Long.class) || fieldClass.equals(long.class)) {
                        f.set(this, Long.parseLong(valueAsString));
                    } else if (fieldClass.equals(Byte.class) || fieldClass.equals(byte.class)) {
                        f.set(this, Byte.parseByte(valueAsString));
                    } else if (fieldClass.equals(Boolean.class) || fieldClass.equals(boolean.class)) {
                        f.set(this, Boolean.parseBoolean(valueAsString));
                    }
                } else if (fieldClass.isAssignableFrom(valueClass)) {
                    // no conversion for other type than String and primitive
                    f.set(this, e.getValue());
                }
            } catch (Exception ex) {
                // nothing to do, no automatic assignment can be done for this field
            }
        }
        current = current.getSuperclass();
    }
}
 
源代码18 项目: termsuite-core   文件: IndexedCorpusModule.java
Slf4JMembersInjector(Field field) {
  this.field = field;
  this.logger = LoggerFactory.getLogger(field.getDeclaringClass());
  field.setAccessible(true);
}
 
源代码19 项目: hub-detect   文件: DetectOptionManager.java
private DetectOption processField(final DetectProperty detectProperty, final String currentValue) {
    try {
        final Field field = DetectProperty.class.getField(detectProperty.name());

        String defaultValue = "";
        if (null != detectProperty.getDefaultValue()) {
            defaultValue = detectProperty.getDefaultValue();
        }

        List<String> validValues = new ArrayList<>();
        boolean isCommaSeparatedList = false;
        boolean strictValidation = false;
        boolean caseSensitiveValidation = false;
        final AcceptableValues acceptableValueAnnotation = field.getAnnotation(AcceptableValues.class);
        if (acceptableValueAnnotation != null) {
            validValues = Arrays.asList(acceptableValueAnnotation.value());
            strictValidation = acceptableValueAnnotation.strict();
            caseSensitiveValidation = acceptableValueAnnotation.caseSensitive();
            isCommaSeparatedList = acceptableValueAnnotation.isCommaSeparatedList();
        }

        String resolvedValue = defaultValue;
        field.setAccessible(true);

        final boolean hasValue = null != currentValue;
        if (defaultValue != null && !defaultValue.trim().isEmpty() && !hasValue) {
            resolvedValue = defaultValue;
            detectConfiguration.setDetectProperty(detectProperty, resolvedValue);
        } else if (hasValue) {
            resolvedValue = currentValue;
        }

        final DetectOptionHelp help = processFieldHelp(field);

        DetectOption detectOption;
        if (isCommaSeparatedList) {
            detectOption = new DetectListOption(detectProperty, strictValidation, caseSensitiveValidation, validValues, help, resolvedValue);
        } else {
            detectOption = new DetectSingleOption(detectProperty, strictValidation, caseSensitiveValidation, validValues, help, resolvedValue);
        }

        return detectOption;
    } catch (IllegalArgumentException | NoSuchFieldException e) {
        logger.error(String.format("Could not resolve field %s: %s", detectProperty.name(), e.getMessage()));
    }
    return null;
}
 
源代码20 项目: datax-web   文件: ReflectionUtil.java
/**
 * 获取私有成员变量的值
 * @param instance 要获取的对象
 * @param filedName 获取的变量名称
 * @return 返回获取变量的信息(需要强转)
 */
public static Object getPrivateField(Object instance, String filedName) throws NoSuchFieldException, IllegalAccessException {
    Field field = instance.getClass().getDeclaredField(filedName);
    field.setAccessible(true);
    return field.get(instance);
}