private void initializePluginAPI(TiWebView webView) { try { synchronized (this.getClass()) { // Initialize if (enumPluginStateOff == null) { Class<?> webSettings = Class.forName("android.webkit.WebSettings"); Class<?> pluginState = Class.forName("android.webkit.WebSettings$PluginState"); Field f = pluginState.getDeclaredField("OFF"); enumPluginStateOff = (Enum<?>) f.get(null); f = pluginState.getDeclaredField("ON"); enumPluginStateOn = (Enum<?>) f.get(null); f = pluginState.getDeclaredField("ON_DEMAND"); enumPluginStateOnDemand = (Enum<?>) f.get(null); internalSetPluginState = webSettings.getMethod("setPluginState", pluginState); // Hidden APIs // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/webkit/WebView.java;h=bbd8b95c7bea66b7060b5782fae4b3b2c4f04966;hb=4db1f432b853152075923499768639e14403b73a#l2558 internalWebViewPause = webView.getClass().getMethod("onPause"); internalWebViewResume = webView.getClass().getMethod("onResume"); } } } catch (ClassNotFoundException e) { Log.e(TAG, "ClassNotFound: " + e.getMessage(), e); } catch (NoSuchMethodException e) { Log.e(TAG, "NoSuchMethod: " + e.getMessage(), e); } catch (NoSuchFieldException e) { Log.e(TAG, "NoSuchField: " + e.getMessage(), e); } catch (IllegalAccessException e) { Log.e(TAG, "IllegalAccess: " + e.getMessage(), e); } }
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) { } }
@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); } }
/** * Compares to consume fields of two object of the same type Note this won't work with proxy * object. * * @param original * @param compare * @return compare value (0 if equals) */ public static int compareConsumeFields(Object original, Object compare) { int value = 0; if (original != null && compare == null) { value = -1; } else if (original == null && compare != null) { value = 1; } else if (original != null && compare != null) { if (original.getClass().isInstance(compare)) { List<Field> fields = getAllFields(original.getClass()); for (Field field : fields) { ConsumeField consume = (ConsumeField) field.getAnnotation(ConsumeField.class); if (consume != null) { try { field.setAccessible(true); value = compareObjects((Comparable) field.get(original), (Comparable) field.get(compare)); if (value != 0) { break; } } catch (IllegalArgumentException | IllegalAccessException ex) { throw new OpenStorefrontRuntimeException("Can't compare object fields", ex); } } } } else { throw new OpenStorefrontRuntimeException( "Can't compare different object types", "Check objects"); } } return value; }
private static void jsonFromField(StringBuilder sb, Object obj, int i, Field f) { if (f.getType().equals(String.class)) { try { String key = f.getName(); String val = String.valueOf(f.get(obj)); if (i != 0) { sb.append(", "); } sb.append("\""); sb.append(key); sb.append("\""); sb.append(":"); sb.append("\""); sb.append(val); sb.append("\""); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } else if (f.getType().equals(Date.class)) { try { String key = f.getName(); Date val = (Date) f.get(obj); if (i != 0) { sb.append(", "); } sb.append("\""); sb.append(key); sb.append("\""); sb.append(":"); // sb.append("\""); sb.append(val.getTime()); // sb.append("\""); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } else if (f.getType().equals(org.json.JSONObject.class)) { try { String key = f.getName(); org.json.JSONObject jobj = (org.json.JSONObject) f.get(obj); if (jobj == null) return; String val = jobj.toString(); if (i != 0) { sb.append(", "); } sb.append("\""); sb.append(key); sb.append("\""); sb.append(":"); sb.append(val); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } }
/** * 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!"); }
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; }
protected SocketImpl swapSocketImpl(Socket socket, SocketImpl socketImpl) throws Exception { Field implField = ReflectionUtil.getDeclaredField(Socket.class, "impl"); SocketImpl oldSocketImpl = (SocketImpl) implField.get(socket); if (socketImpl == null) { Socket unbindSocket = new Socket(); socketImpl = (SocketImpl) implField.get(unbindSocket); Field cmdsockField = ReflectionUtil.getDeclaredField(socketImpl.getClass(), "cmdsock"); cmdsockField.set( socketImpl, new Socket() { @Override public synchronized void close() throws IOException { throw new IOException(); } }); } implField.set(socket, socketImpl); return oldSocketImpl; }
/** * 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()); } } }
@Test public void ignoreClosedStream() throws IOException, NoSuchFieldException, IllegalAccessException { Field bufferField; int i, length; byte expect[], actual[]; length = 2 * SplitInputStream.INITIAL_BUFFER_SIZE; initialize(length, SplitInputStream.INITIAL_BUFFER_SIZE); m_input.close(); bufferField = SplitInputStream.class.getDeclaredField("m_buffer"); bufferField.setAccessible(true); expect = (byte[]) bufferField.get(m_fixture); m_input = m_fixture.getStream(1); for (i = 0; i < length; i++) { assertEquals(m_expect[i] & 0x0FF, m_input.read()); } actual = (byte[]) bufferField.get(m_fixture); assertSame(expect, actual); }
private static void doEnhance(Field field, Object g, int depth) { final SmartDate sd = field.getAnnotation(SmartDate.class); if (sd != null) { final SmartDateType sdt = sd.type(); try { if (sdt.equals(SmartDateType.CreatedDate)) { if (Date.class.isAssignableFrom(field.getType())) { Object obj = field.get(g); if (obj == null) field.set(g, new Date()); } } else if (sdt.equals(SmartDateType.UpdatedDate)) { if (Date.class.isAssignableFrom(field.getType())) { field.setAccessible(true); Object obj = field.get(g); if (obj == null) { field.set(g, new Date()); } else if (!hasDisupdateFlag(g)) { field.set(g, new Date()); } } } } catch (Exception e) { debug("SmartDateUtils#doEnhance : %s, %s", e.getClass().getName(), e.getMessage()); throw new OrigamiUnexpectedException(e); } } }
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; }
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 } }
@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(); } }
@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); }
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; }
/** * Perform one setter operation with the provided value. * * @param instance Instance of class under test to operate on. * @param property Property being tested * @param field Field being tested * @param testVal Test value to use. * @return Optional that will contain an error message if the test failed, otherwise empty. * @throws InvocationTargetException * @throws IllegalAccessException */ private Optional<String> testSetterWithVal( T instance, PropertyDescriptor property, Field field, Object testVal) throws InvocationTargetException, IllegalAccessException { Objects.requireNonNull(instance, "Instance of target class required."); boolean status = true; property.getWriteMethod().invoke(instance, testVal); Object expected, actual; if (property.getPropertyType().isPrimitive()) { expected = String.valueOf(testVal); actual = String.valueOf(field.get(instance)); status = expected.equals(actual); } else { expected = testVal; actual = field.get(instance); if (expected == null) { status = actual == null; } else { status = expected.equals(actual); } } if (status == false) { return Optional.of( String.format( "Failed during setter test: %s. Expected: %s Actual: %s", property.getWriteMethod(), expected, actual)); } return Optional.empty(); }
public String toXML() { String className = getClass().getName(); className = className.substring(className.lastIndexOf(".") + 1, className.length()).toUpperCase(); StringBuffer buffer = new StringBuffer(); buffer.append("<"); buffer.append(className); buffer.append(">"); try { java.lang.reflect.Field[] fields = getClass().getDeclaredFields(); java.lang.reflect.Field field = null; String name = null; int size = fields.length; for (int i = 0; i < size; i++) { field = fields[i]; name = field.getName(); buffer.append("<"); buffer.append(name.toUpperCase()); buffer.append(">"); if (field.get(this) != null) { buffer.append(field.get(this)); } buffer.append("</"); buffer.append(name.toUpperCase()); buffer.append(">"); } } catch (Exception e) { e.printStackTrace(System.err); } buffer.append("</"); buffer.append(className); buffer.append(">"); return buffer.toString(); }
private static void reflectionAppend( Object obj, Object obj1, Class class1, CompareToBuilder comparetobuilder, boolean flag, String as[]) { Field afield[] = class1.getDeclaredFields(); AccessibleObject.setAccessible(afield, true); int i = 0; do { if (i >= afield.length || comparetobuilder.comparison != 0) { return; } Field field = afield[i]; if (!ArrayUtils.contains(as, field.getName()) && field.getName().indexOf('$') == -1 && (flag || !Modifier.isTransient(field.getModifiers())) && !Modifier.isStatic(field.getModifiers())) { try { comparetobuilder.append(field.get(obj), field.get(obj1)); } catch (IllegalAccessException illegalaccessexception) { throw new InternalError("Unexpected IllegalAccessException"); } } i++; } while (true); }
/** Looks inside the given class and finds all declared properties */ protected static Property<?>[] generateProperties(Class<? extends AbstractModel> cls) { ArrayList<Property<?>> properties = new ArrayList<>(); if (cls.getSuperclass() != AbstractModel.class) { properties.addAll( Arrays.asList(generateProperties((Class<? extends AbstractModel>) cls.getSuperclass()))); } // a property is public, static & extends Property for (Field field : cls.getFields()) { if ((field.getModifiers() & Modifier.STATIC) == 0) { continue; } if (!Property.class.isAssignableFrom(field.getType())) { continue; } try { if (((Property<?>) field.get(null)).table == null) { continue; } properties.add((Property<?>) field.get(null)); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } return properties.toArray(new Property<?>[properties.size()]); }
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; }
/** * 设置预编译参数 * * @param ps 预编译 * @param index 序号 * @param t vo模型 * @param f 字段 * @throws IllegalArgumentException * @throws SQLException * @throws IllegalAccessException */ private void setParamter(PreparedStatement ps, int index, T t, Field f) throws IllegalArgumentException, SQLException, IllegalAccessException { if (!f.isAccessible()) { f.setAccessible(true); } if (isBoolean(f)) { ps.setBoolean(index, f.getBoolean(t)); } else if (isInt(f)) { ps.setInt(index, f.getInt(t)); } else if (isLong(f)) { ps.setLong(index, f.getLong(t)); } else if (isString(f)) { ps.setString(index, (String) f.get(t)); } else if (isDate(f)) { Object o = f.get(t); if (o == null) { ps.setDate(index, null); } else { ps.setTimestamp(index, new java.sql.Timestamp(((Date) o).getTime())); } } else if (isByte(f)) { ps.setByte(index, f.getByte(t)); } else if (isChar(f)) { ps.setInt(index, f.getChar(t)); } else if (isDouble(f)) { ps.setDouble(index, f.getDouble(t)); } else if (isFloat(f)) { ps.setFloat(index, f.getFloat(t)); } else { ps.setObject(index, f.get(t)); } }
// 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(); } }
@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); } }
/** * An equals method that checks equality by asserting that the classes are of the exact same type * and that all public fields are equal. * * @param o an instance to compare to * @return true if they are equal, false otherwise */ public boolean equals(final Object o) { if (o == null) return false; if (o.getClass() != getClass()) return false; // Loop through all the fields and check that they are either // null in both objects or equal in both objects for (final Field f : getClass().getFields()) { try { final Object lhs = f.get(this); final Object rhs = f.get(o); if (lhs == null) { if (rhs == null) { // keep going } else if (rhs != null) { return false; } } else { if (lhs.equals(rhs)) { // keep going } else { return false; } } } catch (IllegalAccessException iae) { throw new PicardException( "Could not read field " + f.getName() + " from a " + getClass().getSimpleName()); } } // If we got this far all the fields are equal return true; }
@Override public void writeRecord(T record) throws DataImportException { FileWriter writer = this.getWriter(); StringBuilder stringBuilder = new StringBuilder(); try { boolean flag = false; for (Field field : record.getClass().getDeclaredFields()) { if (!ignoredFields.contains(field.getName())) { field.setAccessible(true); Object value = field.get(record) != null ? field.get(record) : null; if (value == null) { value = "null"; } else if (!"".equals(enclosedBy) && value instanceof String) { value = ((String) value).replaceAll(enclosedBy, escapedBy + enclosedBy); } if (flag) stringBuilder.append(delimiter); stringBuilder.append(enclosedBy).append(value).append(enclosedBy); flag = true; } } } catch (IllegalAccessException e) { e.printStackTrace(); throw new DataImportException(e.getMessage()); } try { writer.write(stringBuilder.toString()); writer.write(terminatedBy); } catch (IOException e) { e.printStackTrace(); throw new DataImportException(e.getMessage()); } }
/** Is c1 an inner class of c2? */ protected boolean isInnerClass(Class c1, final Class c2) { Class c = c1.getDeclaringClass(); if (c == null) { try { final Field f = c1.getField("declaring$Class$Reference$0"); c = (Class) f.get(null); } catch (final Exception e) { } } c1 = c; while (c != null) { if (c == c2) { return true; } c = c.getDeclaringClass(); if (c == null) { try { final Field f = c1.getField("declaring$Class$Reference$0"); c = (Class) f.get(null); } catch (final Exception e) { } } c1 = c; } return false; }
public BasicDBObject converToMGObject(Object obj, Class<?> nameOfClass) { BasicDBObject basicDBObject = new BasicDBObject(); try { Field[] fileds = nameOfClass.getDeclaredFields(); if (fileds != null && fileds.length > 1) { for (Field field : fileds) { field.setAccessible(true); String fieldName = field.getName(); if (fieldName.equals("serialVersionUID")) { continue; } String fieldValue = field.get(obj) == null ? null : field.get(obj).toString(); if (field.getType().getName().equals("java.util.Date")) { if (fieldValue != null) { fieldValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(field.get(obj)); } } if (fieldValue != null) { basicDBObject.put(fieldName, fieldValue); } } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return basicDBObject; }
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); }
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; }