private static boolean isSetException(Score score) throws NoSuchMethodException, NoSuchFieldException, IllegalAccessException, InvocationTargetException { Object craftScore = CRAFT_SCORE.cast(score); Object craftObjective = CRAFT_OBJECTIVE.cast(score.getObjective()); Method craftHandle = CRAFT_OBJECTIVE.getDeclaredMethod("getHandle"); craftHandle.setAccessible(true); Object craftObjectiveHandle = craftHandle.invoke(craftObjective); Field objective = CRAFT_SCORE.getDeclaredField("objective"); objective.setAccessible(true); Object craftScoreboard = checkState(objective.get(craftScore)); Field craftBoard = CRAFT_SCOREBOARD.getDeclaredField("board"); craftBoard.setAccessible(true); Object scoreboard = craftBoard.get(craftScoreboard); Method playerObjectives = SCOREBOARD.getDeclaredMethod("getPlayerObjectives", String.class); playerObjectives.setAccessible(true); Field playerField = CRAFT_SCORE.getDeclaredField("entry"); playerField.setAccessible(true); String playerName = (String) playerField.get(craftScore); Map map = (Map) playerObjectives.invoke(scoreboard, playerName); // return // objective.checkState().board.getPlayerObjectives(playerName).containsKey(objective.getHandle()); return map.containsKey(craftObjectiveHandle); }
public static void cancelListViewBounceShadow(ListView listView) { try { Class<?> c = (Class<?>) Class.forName(AbsListView.class.getName()); Field egtField = c.getDeclaredField("mEdgeGlowTop"); Field egbBottom = c.getDeclaredField("mEdgeGlowBottom"); egtField.setAccessible(true); egbBottom.setAccessible(true); Object egtObject = egtField.get(listView); // this 指的是ListiVew实例 Object egbObject = egbBottom.get(listView); // egtObject.getClass() 实际上是一个 EdgeEffect 其中有两个重要属性 mGlow mEdge // 并且这两个属性都是Drawable类型 Class<?> cc = (Class<?>) Class.forName(egtObject.getClass().getName()); Field mGlow = cc.getDeclaredField("mGlow"); mGlow.setAccessible(true); mGlow.set(egtObject, new ColorDrawable(Color.TRANSPARENT)); mGlow.set(egbObject, new ColorDrawable(Color.TRANSPARENT)); Field mEdge = cc.getDeclaredField("mEdge"); mEdge.setAccessible(true); mEdge.set(egtObject, new ColorDrawable(Color.TRANSPARENT)); mEdge.set(egbObject, new ColorDrawable(Color.TRANSPARENT)); } catch (Exception e) { } }
public static <T> T collapseStructure(T object) { if (hasOnlyNullFields(object)) { return null; } List<Field> fields = getAllFields(object.getClass()); try { for (Field field : fields) { if (!field.isAccessible()) { field.setAccessible(true); } if (field.get(object) != null) { if (field.getType().getName().contains("java.util.List")) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>) field.get(object); List<Object> newList = new ArrayList<Object>(list.size()); boolean isNull = true; for (int i = 0; i < list.size(); i++) { Object o = collapseStructure(list.get(i)); if (o != null) { isNull = false; newList.add(o); } } field.set(object, isNull ? null : newList); continue; } else if (field.getType().getName().contains("java.lang.String")) { if ("".equals(((String) field.get(object)).trim())) { field.set(object, null); } continue; } else if (field.getType().getName().contains("CodeOrText") || field.getType().getName().contains("NameTypeAttribute") || field.getType().getName().contains("PlaceAuthority") || field.getType().getName().contains("Yes")) { Field auxField = field.getType().getDeclaredField("value"); auxField.setAccessible(true); String s = (String) auxField.get(field.get(object)); if ("".equals(s)) { field.set(object, null); } continue; } else { collapseStructure(field.get(object)); } } } } catch (IllegalArgumentException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } catch (IllegalAccessException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } catch (SecurityException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } catch (NoSuchFieldException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } if (hasOnlyNullFields(object)) { return null; } return object; }
public void forceCustomAnnotationHover() throws NoSuchFieldException, IllegalAccessException { Class<SourceViewer> sourceViewerClazz = SourceViewer.class; sourceViewer.setAnnotationHover(new CommentAnnotationHover(null)); // hack for Eclipse 3.5 try { Field hoverControlCreator = TextViewer.class.getDeclaredField("fHoverControlCreator"); hoverControlCreator.setAccessible(true); hoverControlCreator.set(sourceViewer, new CommentInformationControlCreator()); } catch (Throwable t) { // ignore as it may not exist in other versions } // hack for Eclipse 3.5 try { Method ensureMethod = sourceViewerClazz.getDeclaredMethod("ensureAnnotationHoverManagerInstalled"); ensureMethod.setAccessible(true); ensureMethod.invoke(sourceViewer); } catch (Throwable t) { // ignore as it may not exist in other versions } Field hoverManager = SourceViewer.class.getDeclaredField("fVerticalRulerHoveringController"); hoverManager.setAccessible(true); AnnotationBarHoverManager manager = (AnnotationBarHoverManager) hoverManager.get(sourceViewer); if (manager != null) { Field annotationHover = AnnotationBarHoverManager.class.getDeclaredField("fAnnotationHover"); annotationHover.setAccessible(true); IAnnotationHover hover = (IAnnotationHover) annotationHover.get(manager); annotationHover.set(manager, new CommentAnnotationHover(hover)); } sourceViewer.showAnnotations(true); sourceViewer.showAnnotationsOverview(true); }
/** * The value of field {@code field} of object {@code object}, returned with static type {@code * expectedType}. The value is read, even on private fields. The security settings must allow * this. */ @MethodContract( pre = { @Expression("object != null"), @Expression("field != null"), @Expression("expectedType != null") }, post = @Expression("field.get(object)"), exc = @Throw( type = ClassCastException.class, cond = @Expression("! fieldValue(object, field) instanceof expectedType"))) public static final <_T_> _T_ fieldValue(Object object, Field field, Class<_T_> expectedType) throws ClassCastException { assert preArgumentNotNull(object, "object"); assert preArgumentNotNull(field, "field"); assert preArgumentNotNull(expectedType, "expectedType"); boolean oldAccessible = field.isAccessible(); field.setAccessible(true); _T_ result = null; try { result = expectedType.cast(field.get(object)); // ClassCastException } catch (IllegalArgumentException exc) { unexpectedException(exc); } catch (IllegalAccessException exc) { unexpectedException(exc); } field.setAccessible(oldAccessible); return result; }
/** * Gets the primary activity without calling from an Activity class * * @return the main Activity */ @TargetApi(Build.VERSION_CODES.KITKAT) public static Activity getActivity() { /*ActivityManager am = (ActivityManager)getContext().getSystemService(Context.ACTIVITY_SERVICE); ComponentName cn = am.getRunningTasks(1).get(0).topActivity;*/ try { Class activityThreadClass = Class.forName("android.app.ActivityThread"); Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null); Field activitiesField = activityThreadClass.getDeclaredField("mActivities"); activitiesField.setAccessible(true); ArrayMap activities = (ArrayMap) activitiesField.get(activityThread); for (Object activityRecord : activities.values()) { Class activityRecordClass = activityRecord.getClass(); Field pausedField = activityRecordClass.getDeclaredField("paused"); pausedField.setAccessible(true); if (!pausedField.getBoolean(activityRecord)) { Field activityField = activityRecordClass.getDeclaredField("activity"); activityField.setAccessible(true); return (Activity) activityField.get(activityRecord); } } } catch (final java.lang.Throwable e) { // handle exception throw new IllegalArgumentException("No activity could be retrieved!"); } throw new IllegalArgumentException("No activity could be found!"); }
// for android 4.1+ private void enable_x_domain_41_after() { try { Field webviewclassic_field = WebView.class.getDeclaredField("mProvider"); webviewclassic_field.setAccessible(true); Object webviewclassic = webviewclassic_field.get(this); Field webviewcore_field = webviewclassic.getClass().getDeclaredField("mWebViewCore"); webviewcore_field.setAccessible(true); Object mWebViewCore = webviewcore_field.get(webviewclassic); Field nativeclass_field = webviewclassic.getClass().getDeclaredField("mNativeClass"); nativeclass_field.setAccessible(true); Object mNativeClass = nativeclass_field.get(webviewclassic); Method method = mWebViewCore .getClass() .getDeclaredMethod( "nativeRegisterURLSchemeAsLocal", new Class[] {int.class, String.class}); method.setAccessible(true); method.invoke(mWebViewCore, mNativeClass, "http"); method.invoke(mWebViewCore, mNativeClass, "https"); } catch (Exception e) { Log.d("wokao", "enablecrossdomain error"); e.printStackTrace(); } }
public static Map<String, List<String>> getZkWatch(ZkClient client) throws Exception { Map<String, List<String>> lists = new HashMap<String, List<String>>(); ZkConnection connection = ((ZkConnection) client.getConnection()); ZooKeeper zk = connection.getZookeeper(); java.lang.reflect.Field field = getField(zk.getClass(), "watchManager"); field.setAccessible(true); Object watchManager = field.get(zk); java.lang.reflect.Field field2 = getField(watchManager.getClass(), "dataWatches"); field2.setAccessible(true); HashMap<String, Set<Watcher>> dataWatches = (HashMap<String, Set<Watcher>>) field2.get(watchManager); field2 = getField(watchManager.getClass(), "existWatches"); field2.setAccessible(true); HashMap<String, Set<Watcher>> existWatches = (HashMap<String, Set<Watcher>>) field2.get(watchManager); field2 = getField(watchManager.getClass(), "childWatches"); field2.setAccessible(true); HashMap<String, Set<Watcher>> childWatches = (HashMap<String, Set<Watcher>>) field2.get(watchManager); lists.put("dataWatches", new ArrayList<String>(dataWatches.keySet())); lists.put("existWatches", new ArrayList<String>(existWatches.keySet())); lists.put("childWatches", new ArrayList<String>(childWatches.keySet())); return lists; }
@Test public void testSetArguments() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { TestBean bean = new TestBean(); TestMethodProperty<String> property = new TestMethodProperty<String>(bean, "name"); Object[] getArgs = property.getGetArgs(); Object[] setArgs = property.getSetArgs(); Field getArgsField = TestMethodProperty.class.getDeclaredField("getArgs"); getArgsField.setAccessible(true); Field setArgsField = TestMethodProperty.class.getDeclaredField("setArgs"); setArgsField.setAccessible(true); Assert.assertSame( "setArguments method sets non-default instance" + " of empty Object array for getArgs", getArgsField.get(property), getArgs); Assert.assertSame( "setArguments method sets non-default instance" + " of empty Object array for setArgs", setArgsField.get(property), setArgs); }
public static void setValue(Field field, Object target, Object value) { if (target == null) { throw new IllegalArgumentException("Parameter 'target' can't be null"); } if (field == null) { throw new IllegalArgumentException("Parameter 'field' can't be null"); } boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } try { field.set(target, value); } catch (Exception ex) { throw new GrapheneTestEnricherException( "During enriching of " + NEW_LINE + target.getClass() + NEW_LINE + " the field " + NEW_LINE + field + " was not able to be set! Check the cause!", ex); } if (!accessible) { field.setAccessible(false); } }
@SuppressWarnings("rawtypes") @Override public void overwriteVillagerAI(LivingEntity villager) { try { EntityVillager ev = ((CraftVillager) villager).getHandle(); Field goalsField = EntityInsentient.class.getDeclaredField("goalSelector"); goalsField.setAccessible(true); PathfinderGoalSelector goals = (PathfinderGoalSelector) goalsField.get(ev); Field listField = PathfinderGoalSelector.class.getDeclaredField("a"); listField.setAccessible(true); List list = (List) listField.get(goals); list.clear(); listField = PathfinderGoalSelector.class.getDeclaredField("b"); listField.setAccessible(true); list = (List) listField.get(goals); list.clear(); goals.a(0, new PathfinderGoalFloat(ev)); goals.a(1, new PathfinderGoalTradeWithPlayer(ev)); goals.a(1, new PathfinderGoalLookAtTradingPlayer(ev)); goals.a(2, new PathfinderGoalLookAtPlayer(ev, EntityHuman.class, 12.0F, 1.0F)); } catch (Exception e) { e.printStackTrace(); } }
public static final void checkDataVersion(final Object data1, final Object data2) { if (null != data1) { try { final Field data1Version = data1.getClass().getDeclaredField("version"); // LOG.debug("find updId in methodinvocation"); data1Version.setAccessible(true); final long data1Verlong = data1Version.getLong(data1); if (null == data2) { final Code3gException pos3ge = new Code3gException("B341005"); pos3ge.setStatus(1); throw pos3ge; } final Field data2Version = data2.getClass().getDeclaredField("version"); // LOG.debug("find updId in methodinvocation"); data2Version.setAccessible(true); final long data2Verlong = data2Version.getLong(data2); if (data1Verlong != data2Verlong) { final Code3gException pos3ge = new Code3gException("B341005"); pos3ge.setStatus(1); throw pos3ge; } } catch (NoSuchFieldException e) { LOG.error("check version error, " + e.getMessage(), e); } catch (IllegalArgumentException e) { LOG.error("check version error, " + e.getMessage(), e); } catch (IllegalAccessException e) { LOG.error("check version error, " + e.getMessage(), e); } } }
@SuppressWarnings("rawtypes") private void initReflection() { Object webViewObject = webView; Class webViewClass = WebView.class; try { Field f = webViewClass.getDeclaredField("mProvider"); f.setAccessible(true); webViewObject = f.get(webView); webViewClass = webViewObject.getClass(); } catch (Throwable e) { // mProvider is only required on newer Android releases. } try { Field f = webViewClass.getDeclaredField("mWebViewCore"); f.setAccessible(true); webViewCore = f.get(webViewObject); if (webViewCore != null) { sendMessageMethod = webViewCore.getClass().getDeclaredMethod("sendMessage", Message.class); sendMessageMethod.setAccessible(true); } } catch (Throwable e) { initFailed = true; Log.e(LOG_TAG, "PrivateApiBridgeMode failed to find the expected APIs.", e); } }
private Map<int[], Integer> getExistingColorStates(TextView view) { Map<int[], Integer> map = new LinkedHashMap<int[], Integer>(); ColorStateList textColors = view.getTextColors(); if (textColors != null) { try { Field specsField = textColors.getClass().getDeclaredField("mStateSpecs"); specsField.setAccessible(true); int[][] stateSpecs = (int[][]) specsField.get(textColors); Field colorsField = textColors.getClass().getDeclaredField("mColors"); colorsField.setAccessible(true); int[] colors = (int[]) colorsField.get(textColors); // These all should match if (stateSpecs != null && colors != null && stateSpecs.length == colors.length) { // load the map with the existing states for (int i = 0; i < stateSpecs.length; i++) { map.put(stateSpecs[i], colors[i]); } } } catch (Exception e) { PXLog.e(PXViewStyleAdapter.class.getSimpleName(), e, "Error getting the state set"); } finally { } } return map; }
private Map<String, String> readService(Service service) { Map<String, String> attributes = new HashMap<>(); for (Field field : service.getClass().getDeclaredFields()) { boolean include = false; include |= field.getName().endsWith("Time"); include |= field.getName().endsWith("Distance"); include |= field.getName().endsWith("Agent"); include |= field.getName().equals("startLinkId"); include |= field.getName().equals("id"); if (include) { field.setAccessible(true); try { Object value = field.get(service); if (value instanceof MobsimAgent) { value = (Object) ((MobsimAgent) value).getId().toString(); } attributes.put(field.getName(), value.toString()); } catch (DOMException | IllegalArgumentException | IllegalAccessException e) { } field.setAccessible(false); } } return attributes; }
/** * 将父类对像转成子类的对象,不能有带参数构造方法 仅仅是将同名的字段值复制 * * @param parent * @param childClass * @return */ public static Object castToChild(Object parent, Class childClass) { // if(parent instanceof type) // { // return parent; // } Class parentClass = parent.getClass(); if (parentClass == childClass) return parent; if (parentClass.isAssignableFrom(childClass)) { Field[] parentFields = parentClass.getDeclaredFields(); try { Object child = childClass.newInstance(); for (Field field : parentFields) { field.setAccessible(true); Field childField = childClass.getSuperclass().getDeclaredField(field.getName()); childField.setAccessible(true); childField.set(child, field.get(parent)); } return child; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } return null; }
@Override public boolean isValid(final Object target, final ConstraintValidatorContext context) { try { Field fieldObj = target.getClass().getDeclaredField(flightField); Field fieldSeats = target.getClass().getDeclaredField(seatsField); fieldObj.setAccessible(true); fieldSeats.setAccessible(true); Flight flight = (Flight) fieldObj.get(target); if (flight == null) return false; Integer seats = (Integer) fieldSeats.get(target); if (seats == null) return false; int count = 0; for (Reservation reservation : flight.getReservations()) { if (reservation.getState() != StateChoices.CANCELED && !target.equals(reservation)) { count += reservation.getSeats(); } } return flight.getSeats() >= count + seats; } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
protected void delay() { Object ca = configAdminTracker.getService(); if (ca != null) { try { Field caf = ca.getClass().getDeclaredField("configurationManager"); caf.setAccessible(true); Object cm = caf.get(ca); Field cmf = cm.getClass().getDeclaredField("updateThread"); cmf.setAccessible(true); Object ut = cmf.get(cm); Method utm = ut.getClass().getDeclaredMethod("schedule"); utm.setAccessible(true); UpdateThreadSignalTask signalTask = new UpdateThreadSignalTask(); utm.invoke(ut, signalTask); signalTask.waitSignal(); return; } catch (AssertionFailedError afe) { throw afe; } catch (Throwable t) { // ignore any problem and revert to timed delay (might log this) } } // no configadmin or failure while setting up task try { Thread.sleep(300); } catch (InterruptedException ie) { // dont care } }
/** * copy * * @param dest * @param orig * @param ignoreNull 忽略null,即orig为空的字段不做copy * @author Joeson */ public static void copy(Object dest, Object orig, boolean ignoreNull) { if (null == dest || null == orig) { return; } Class destClz = dest.getClass(); Class origClz = orig.getClass(); Field[] destFields = destClz.getDeclaredFields(); Field[] origFields = origClz.getDeclaredFields(); for (Field origField : origFields) { try { String fieldName = origField.getName(); origField.setAccessible(true); if (!ignoreNull || null != origField.get(orig)) { for (Field destField : destFields) { if (destField.getName().equals(origField.getName()) && destField.getType().equals(origField.getType())) { destField.setAccessible(true); Object o = origField.get(orig); BeanUtils.copyProperty(dest, fieldName, o); break; } } } } catch (Exception e) { logger.error("copyNonNull exception.", e); throw new RuntimeException("copyNonNull exception.." + e.getMessage()); } } }
public int describe(Reader contents, IContentDescription description) throws IOException { try { final Field documentReaderField = contents.getClass().getDeclaredField("in"); documentReaderField.setAccessible(true); final Object documentReader = documentReaderField.get(contents); final Field fDocumentField = documentReader.getClass().getDeclaredField("fDocument"); fDocumentField.setAccessible(true); final Object fDocument = fDocumentField.get(documentReader); final Field fDocumentListenersField = fDocument .getClass() .getSuperclass() .getSuperclass() .getDeclaredField("fDocumentListeners"); fDocumentListenersField.setAccessible(true); final ListenerList fDocumentListeners = (ListenerList) fDocumentListenersField.get(fDocument); final Object[] listeners = fDocumentListeners.getListeners(); for (Object listener : listeners) { try { final Field fFileField = listener.getClass().getEnclosingClass().getSuperclass().getDeclaredField("fFile"); fFileField.setAccessible(true); // get enclosing instance of listener final Field thisField = listener.getClass().getDeclaredField("this$0"); thisField.setAccessible(true); Object enclosingObject = thisField.get(listener); Object fFile = fFileField.get(enclosingObject); if (fFile instanceof IFile) { IFile file = (IFile) fFile; if (isValidFile(file)) { return VALID; } } } catch (Exception e) { } } } catch (Exception e) { // ignore errors } return INVALID; }
public static boolean tryWaitZkEventsCleaned(ZkClient zkclient) throws Exception { java.lang.reflect.Field field = getField(zkclient.getClass(), "_eventThread"); field.setAccessible(true); Object eventThread = field.get(zkclient); // System.out.println("field: " + eventThread); java.lang.reflect.Field field2 = getField(eventThread.getClass(), "_events"); field2.setAccessible(true); BlockingQueue queue = (BlockingQueue) field2.get(eventThread); // System.out.println("field2: " + queue + ", " + queue.size()); if (queue == null) { LOG.error("fail to get event-queue from zkclient. skip waiting"); return false; } for (int i = 0; i < 20; i++) { if (queue.size() == 0) { return true; } Thread.sleep(100); System.out.println("pending zk-events in queue: " + queue); } return false; }
public Credentials readCredentials(String credentialsPath) throws IOException, IllegalArgumentException, IllegalAccessException { Properties prop = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream stream = loader.getResourceAsStream(credentialsPath); prop.load(stream); Credentials c = new Credentials(); Field[] declaredFields = Credentials.class.getDeclaredFields(); for (int x = 0, xMax = declaredFields.length; x < xMax; x++) { Field field = declaredFields[x]; String value = prop.getProperty(field.getName(), null); if (value != null) { boolean accessible = field.isAccessible(); // If it's a private field we can: get declared getter method and use it, or modify the // accessibility of the field and edit it field.setAccessible(true); field.set(c, value); field.setAccessible(accessible); } } return c; }
/** * Dynamically register a native library path. This relies on a specific implementation detail of * ClassLoader: it's usr_paths property. * * @param path Library path to add * @return {@code true} if the library path could be added successfully */ protected boolean registerNativeLibraryPath(String path) { if (path == null) { throw new NullPointerException(); } path = path.trim(); try { Field f = ClassLoader.class.getDeclaredField("usr_paths"); boolean accessible = f.isAccessible(); f.setAccessible(true); try { String[] paths = (String[]) f.get(null); // Make sure the path isn't already registered for (String p : paths) { if (p.equals(path)) { return true; // Success, it's already there! } } String[] newPaths = new String[paths.length + 1]; System.arraycopy(paths, 0, newPaths, 0, paths.length); newPaths[paths.length] = path; f.set(null, newPaths); // Success! return true; } finally { f.setAccessible(accessible); } } catch (Exception ex) { // Something went wrong, definitely not successful return false; } }
private WifiConfiguration getHtcWifiApConfiguration(WifiConfiguration standard) { WifiConfiguration htcWifiConfig = standard; try { Field mWifiApProfileField = WifiConfiguration.class.getDeclaredField("mWifiApProfile"); mWifiApProfileField.setAccessible(true); Object apProfile = mWifiApProfileField.get(htcWifiConfig); mWifiApProfileField.setAccessible(false); if (apProfile != null) { Field ssidField = apProfile.getClass().getDeclaredField("SSID"); htcWifiConfig.SSID = (String) ssidField.get(apProfile); } } catch (Exception e) { Log.e(tag, "" + e.getMessage(), e); } // not working in htc /* * try { Object mWifiApProfileValue = BeanUtils.getProperty(standard, * "mWifiApProfile"); * * if (mWifiApProfileValue != null) { htcWifiConfig.SSID = * (String)BeanUtils.getProperty(mWifiApProfileValue, "SSID"); } } catch * (Exception e) { Log.e(tag, "" + e.getMessage(), e); } */ return htcWifiConfig; }
Field[] keyFields() { Class c = clazz; try { List<Field> fields = new ArrayList<Field>(); while (!c.equals(Object.class)) { for (Field field : c.getDeclaredFields()) { // TODO: add cashe field->isAnnotationPresent if (InternalCache.isEnableAnnotationPresent()) { if (InternalCache.isAnnotationPresent(Id.class, field) || InternalCache.isAnnotationPresent(EmbeddedId.class, field)) { field.setAccessible(true); fields.add(field); } } else { if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) { field.setAccessible(true); fields.add(field); } } } c = c.getSuperclass(); } final Field[] f = fields.toArray(new Field[fields.size()]); if (f.length == 0) { throw new UnexpectedException("Cannot get the object @Id for an object of type " + clazz); } return f; } catch (Exception e) { throw new UnexpectedException( "Error while determining the object @Id for an object of type " + clazz); } }
private static void showFields(Object obj) { Class c = obj.getClass(); for (Field field : c.getDeclaredFields()) { int modifiers = 0; try { Show show = field.getAnnotation(Show.class); if (show == null) { System.out.println("skip field " + field.getName()); continue; } System.out.println("Name = " + show.name()); modifiers = field.getModifiers(); if ((modifiers & Modifier.PRIVATE) != 0) { System.out.print("private "); field.setAccessible(true); } if ((modifiers & Modifier.PUBLIC) != 0) System.out.print("public "); if (modifiers == 0) { System.out.print("package local"); field.setAccessible(true); } System.out.println(field.getName() + " = " + field.get(obj) + " " + modifiers); } catch (IllegalAccessException e) { System.out.println(e.getMessage() + " " + field.getName() + " " + modifiers); e.printStackTrace(); } } }
private void readObject(java.io.ObjectInputStream in) throws IOException { float x = in.readFloat(); float y = in.readFloat(); float z = in.readFloat(); String world = in.readUTF(); World w = Spout.getEngine().getWorld(world); try { Field field; field = Vector3.class.getDeclaredField("x"); field.setAccessible(true); field.set(this, x); field = Vector3.class.getDeclaredField("y"); field.setAccessible(true); field.set(this, y); field = Vector3.class.getDeclaredField("z"); field.setAccessible(true); field.set(this, z); field = Point.class.getDeclaredField("world"); field.setAccessible(true); field.set(this, w); } catch (Exception e) { if (Spout.debugMode()) { e.printStackTrace(); } } }
/** * This method returns the serialization of the element provided. * * @param element the element to serialize * @param tabIndentIdx the number of tab indentation needed (only for text indented json) * @return the serialization string * @throws OAException */ private String serializeOAElement(OpenAnnotationElement element, int tabIndentIdx) throws OAException { String serialization = ""; try { List<Field> annotatedFields = selectAnnotatedFields(element, element.getClass()); int fieldIdx = 0; tabIndentIdx++; for (Field field : annotatedFields) { fieldIdx++; OASerializableField annotation = field.getAnnotation(OASerializableField.class); String annotationValue = annotation.value(); if ("DEFAULT_VALUE".equals(annotationValue)) { annotationValue = field.getName(); } field.setAccessible(true); serialization += serializeObject( annotationValue, field.get(element), tabIndentIdx, fieldIdx == annotatedFields.size(), true); field.setAccessible(false); } } catch (Exception e) { throw new OAException(OAException.SERIALIZATIONERROR, e); } return serialization; }
private void registerCommands() { try { commandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap"); commandMap.setAccessible(true); knownCommands = SimpleCommandMap.class.getDeclaredField("knownCommands"); knownCommands.setAccessible(true); } catch (Exception e) { /* do nothing */ } if (commandMap != null && knownCommands != null) { Iterator<Map.Entry<String[], TNECommand>> i = commands.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String[], TNECommand> entry = i.next(); for (String s : entry.getKey()) { if (entry.getValue().activated("", "")) { if (registered(s)) { unregister(s); } register(s); } } } } }
public void SetAlertDialog(DialogInterface arg0, boolean show) { if (show) { try { Field mField = arg0.getClass().getSuperclass().getDeclaredField("mShowing"); mField.setAccessible(true); mField.set(arg0, true); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { Field mField = arg0.getClass().getSuperclass().getDeclaredField("mShowing"); mField.setAccessible(true); mField.set(arg0, false); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }