Java Code Examples for java.lang.reflect.Field#setAccessible()
The following examples show how to use
java.lang.reflect.Field#setAccessible() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VillagerItemShop.java From BedwarsRel with GNU General Public License v3.0 | 6 votes |
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; }
Example 2
Source File: InfluxDbSenderProviderTest.java From graylog-plugin-metrics-reporter with GNU General Public License v3.0 | 6 votes |
@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()); }
Example 3
Source File: ExcelUtil.java From albedo with GNU Lesser General Public License v3.0 | 6 votes |
/** * 填充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++); } } }
Example 4
Source File: BaseBuilder.java From mykit-db-sync with Apache License 2.0 | 6 votes |
/** * 解析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; }
Example 5
Source File: JsonDataModelInjector.java From onos with Apache License 2.0 | 6 votes |
/** * 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); } }
Example 6
Source File: MixAll.java From rocketmq-read with Apache License 2.0 | 6 votes |
/** * 对象变成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; }
Example 7
Source File: ReflectionUtils.java From FastAsyncWorldedit with GNU General Public License v3.0 | 5 votes |
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; } }
Example 8
Source File: StatusBarUtil.java From CoordinatorLayoutExample with Apache License 2.0 | 5 votes |
/** * 设置状态栏图标为深色和魅族特定的文字风格 * 可以用来判断是否为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; }
Example 9
Source File: GitlabHTTPRequestor.java From java-gitlab-api with Apache License 2.0 | 5 votes |
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; }
Example 10
Source File: TestZooKeeperClient.java From distributedlog with Apache License 2.0 | 5 votes |
@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()); }
Example 11
Source File: BaseSearchUpdateExecutor.java From search-spring-boot-starter with Apache License 2.0 | 5 votes |
/** * 根据主键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() + "}"); } }
Example 12
Source File: Point.java From influxdb-java with MIT License | 5 votes |
/** * 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; }
Example 13
Source File: ScopFactoryTest.java From biojava with GNU Lesser General Public License v2.1 | 5 votes |
@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); }
Example 14
Source File: UtilUnsafe.java From aa with Apache License 2.0 | 5 votes |
/** 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); } }
Example 15
Source File: LineClientBuildersTest.java From line-bot-sdk-java with Apache License 2.0 | 5 votes |
@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/")); }
Example 16
Source File: IgniteHadoopFileSystemClientSelfTest.java From ignite with Apache License 2.0 | 4 votes |
/** * 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); }
Example 17
Source File: JavaExecutable.java From scheduling with GNU Affero General Public License v3.0 | 4 votes |
/** * 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(); } }
Example 18
Source File: IndexedCorpusModule.java From termsuite-core with Apache License 2.0 | 4 votes |
Slf4JMembersInjector(Field field) { this.field = field; this.logger = LoggerFactory.getLogger(field.getDeclaringClass()); field.setAccessible(true); }
Example 19
Source File: DetectOptionManager.java From hub-detect with Apache License 2.0 | 4 votes |
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; }
Example 20
Source File: ReflectionUtil.java From datax-web with MIT License | 2 votes |
/** * 获取私有成员变量的值 * @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); }