List of usage examples for java.lang.reflect Field setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
From source file:com.vk.sdk.api.model.ParseUtils.java
/** * Parses object with follow rules:// w w w .j a va2 s .co m * * 1. All fields should had a public access. * 2. The name of the filed should be fully equal to name of JSONObject key. * 3. Supports parse of all Java primitives, all {@link String}, * arrays of primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s, * list implementation line {@link com.vk.sdk.api.model.VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdk.api.model.VKPhotoSizes}, * {@link com.vk.sdk.api.model.VKApiModel}s. * * 4. Boolean fields defines by vk_int == 1 expression. * @param object object to initialize * @param source data to read values * @return initialized according with given data object * @throws JSONException if source object structure is invalid */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException { if (source.has("response")) { source = source.optJSONObject("response"); } if (source == null) { return object; } for (Field field : object.getClass().getFields()) { field.setAccessible(true); String fieldName = field.getName(); Class<?> fieldType = field.getType(); Object value = source.opt(fieldName); if (value == null) { continue; } try { if (fieldType.isPrimitive() && value instanceof Number) { Number number = (Number) value; if (fieldType.equals(int.class)) { field.setInt(object, number.intValue()); } else if (fieldType.equals(long.class)) { field.setLong(object, number.longValue()); } else if (fieldType.equals(float.class)) { field.setFloat(object, number.floatValue()); } else if (fieldType.equals(double.class)) { field.setDouble(object, number.doubleValue()); } else if (fieldType.equals(boolean.class)) { field.setBoolean(object, number.intValue() == 1); } else if (fieldType.equals(short.class)) { field.setShort(object, number.shortValue()); } else if (fieldType.equals(byte.class)) { field.setByte(object, number.byteValue()); } } else { Object result = field.get(object); if (value.getClass().equals(fieldType)) { result = value; } else if (fieldType.isArray() && value instanceof JSONArray) { result = parseArrayViaReflection((JSONArray) value, fieldType); } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKList.class.equals(fieldType)) { ParameterizedType genericTypes = (ParameterizedType) field.getGenericType(); Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0]; if (VKApiModel.class.isAssignableFrom(genericType) && Parcelable.class.isAssignableFrom(genericType) && Identifiable.class.isAssignableFrom(genericType)) { if (value instanceof JSONArray) { result = new VKList((JSONArray) value, genericType); } else if (value instanceof JSONObject) { result = new VKList((JSONObject) value, genericType); } } } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) { result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value); } field.set(object, result); } } catch (InstantiationException e) { throw new JSONException(e.getMessage()); } catch (IllegalAccessException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodException e) { throw new JSONException(e.getMessage()); } catch (InvocationTargetException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodError e) { // ?????????? ???????: // ?? ?? ????????, ?? ? ????????? ???????? getFields() ???????? ??? ???. // ?????? ? ??????? ???????????, ????????? ?? ? ????????, ?????? Android ? ???????? ????????? ??????????. throw new JSONException(e.getMessage()); } } return object; }
From source file:com.vk.sdkweb.api.model.ParseUtils.java
/** * Parses object with follow rules:/*from www .j a va2s .c o m*/ * * 1. All fields should had a public access. * 2. The name of the filed should be fully equal to name of JSONObject key. * 3. Supports parse of all Java primitives, all {@link java.lang.String}, * arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s, * list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes}, * {@link com.vk.sdkweb.api.model.VKApiModel}s. * * 4. Boolean fields defines by vk_int == 1 expression. * * @param object object to initialize * @param source data to read values * @param <T> type of result * @return initialized according with given data object * @throws JSONException if source object structure is invalid */ @SuppressWarnings("rawtypes") public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException { if (source.has("response")) { source = source.optJSONObject("response"); } if (source == null) { return object; } for (Field field : object.getClass().getFields()) { field.setAccessible(true); String fieldName = field.getName(); Class<?> fieldType = field.getType(); Object value = source.opt(fieldName); if (value == null) { continue; } try { if (fieldType.isPrimitive() && value instanceof Number) { Number number = (Number) value; if (fieldType.equals(int.class)) { field.setInt(object, number.intValue()); } else if (fieldType.equals(long.class)) { field.setLong(object, number.longValue()); } else if (fieldType.equals(float.class)) { field.setFloat(object, number.floatValue()); } else if (fieldType.equals(double.class)) { field.setDouble(object, number.doubleValue()); } else if (fieldType.equals(boolean.class)) { field.setBoolean(object, number.intValue() == 1); } else if (fieldType.equals(short.class)) { field.setShort(object, number.shortValue()); } else if (fieldType.equals(byte.class)) { field.setByte(object, number.byteValue()); } } else { Object result = field.get(object); if (value.getClass().equals(fieldType)) { result = value; } else if (fieldType.isArray() && value instanceof JSONArray) { result = parseArrayViaReflection((JSONArray) value, fieldType); } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKList.class.equals(fieldType)) { ParameterizedType genericTypes = (ParameterizedType) field.getGenericType(); Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0]; if (VKApiModel.class.isAssignableFrom(genericType) && Parcelable.class.isAssignableFrom(genericType) && Identifiable.class.isAssignableFrom(genericType)) { if (value instanceof JSONArray) { result = new VKList((JSONArray) value, genericType); } else if (value instanceof JSONObject) { result = new VKList((JSONObject) value, genericType); } } } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) { result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value); } field.set(object, result); } } catch (InstantiationException e) { throw new JSONException(e.getMessage()); } catch (IllegalAccessException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodException e) { throw new JSONException(e.getMessage()); } catch (InvocationTargetException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodError e) { // ?: // , getFields() . // ? ? ?, ? ?, Android ? . throw new JSONException(e.getMessage()); } } return object; }
From source file:com.wavemaker.tools.ws.XJCCompiler.java
@SuppressWarnings("deprecation") public static S2JJAXBModel createSchemaModel(Map<String, Element> schemas, List<com.wavemaker.tools.io.File> bindingFiles, String packageName, Set<String> auxiliaryClasses, WebServiceType type) throws GenerationException { if (schemas == null || schemas.isEmpty()) { return null; }/*w w w . j a va2 s . c o m*/ SchemaCompiler sc = XJC.createSchemaCompiler(); if (type == WebServiceType.SOAP) { // mimic what JAXWS's WsimportTool would do for SEI class name and // JAXB class name collision. ClassNameAllocator allocator = new ClassNameAllocatorImpl( new SimpleClassNameCollector(auxiliaryClasses)); sc.setClassNameAllocator(allocator); } JAXBCompilerErrorListener listener = new JAXBCompilerErrorListener(); sc.setErrorListener(listener); try { Field ncc = sc.getClass().getDeclaredField("NO_CORRECTNESS_CHECK"); ncc.setAccessible(true); ncc.set(sc, true); } catch (Exception e) { throw new GenerationException(e); } if (packageName != null) { sc.setDefaultPackageName(packageName); } for (Entry<String, Element> entry : schemas.entrySet()) { Element schema = entry.getValue(); // need to remove xsd:import or you will get element/type already // defined error during sc.bind() Element updatedSchema = removeImportElement(schema); sc.parseSchema(entry.getKey(), updatedSchema); } if (bindingFiles != null) { for (com.wavemaker.tools.io.File file : bindingFiles) { try { InputSource inputSource = new InputSource(file.getContent().asInputStream()); // cftempfix - if binding files are NOT ALWAYS local files (eg. mongo DB file), we may need to // correctly implement // logic for none-local file case. if (file instanceof LocalFile) { File f = ((LocalFile) file).getLocalFile(); inputSource.setSystemId(f.toURI().toString()); } else { inputSource.setSystemId(ResourceURL.get(file).toURI().toString()); } sc.parseSchema(inputSource); } catch (MalformedURLException e) { throw new GenerationException(e); } catch (URISyntaxException e) { throw new GenerationException(e); } } } Options options = sc.getOptions(); options.target = SpecVersion.V2_1; // suppress generation of package level annotations options.packageLevelAnnotations = false; // generate setter methods for Collection based properties options.activePlugins.add(new com.sun.tools.xjc.addon.collection_setter_injector.PluginImpl()); // replace isXXX with getXXX for Boolean type properties options.activePlugins.add(new com.wavemaker.tools.ws.jaxb.boolean_getter.PluginImpl()); S2JJAXBModel model = sc.bind(); if (listener.hasError) { throw listener.getException(); } return model; }
From source file:gumga.framework.presentation.api.CSVGeneratorAPI.java
public static StringBuilder objectToCsvLine(Object gm) { StringBuilder sb = new StringBuilder(); for (Field f : getAllAtributes(gm.getClass())) { try {// www . jav a 2s.com f.setAccessible(true); if (f.get(gm) != null) { Field idField = getIdField(f.getType()); if (idField != null) { idField.setAccessible(true); Object idValue = idField.get(f.get(gm)); sb.append(idValue.toString()); } else if (f.getType().equals(Date.class)) { sb.append(SDF.format(f.get(gm))); } else { sb.append(f.get(gm).toString()); } } } catch (Exception ex) { log.error("erro ao criar linha csv", ex); } sb.append(CSV_SEPARATOR); } sb.deleteCharAt(sb.length() - 1); sb.append(CSV_LINE_DELIMITER); return sb; }
From source file:org.cybercat.automation.annotations.AnnotationBuilder.java
public static final <T extends IFeature> void processCCPageObject(T entity) throws AutomationFrameworkException { for (Field field : entity.getClass().getDeclaredFields()) { field.setAccessible(true); if (field.getAnnotation(CCPageObject.class) != null) { createPageObjectField(entity, field); } else if (field.getAnnotation(CCProperty.class) != null) { processPropertyField(entity, field); }//from w ww .j ava 2s . c o m } }
From source file:com.bt.download.android.gui.UniversalScanner.java
private static Uri nativeScanFile(Context context, String path) { try {//from w w w. jav a 2 s .c om File f = new File(path); Class<?> clazz = Class.forName("android.media.MediaScanner"); Constructor<?> mediaScannerC = clazz.getDeclaredConstructor(Context.class); Object scanner = mediaScannerC.newInstance(context); Field mClientF = clazz.getDeclaredField("mClient"); mClientF.setAccessible(true); Object mClient = mClientF.get(scanner); Method scanSingleFileM = clazz.getDeclaredMethod("scanSingleFile", String.class, String.class, String.class); Uri fileUri = (Uri) scanSingleFileM.invoke(scanner, f.getAbsolutePath(), "external", "data/raw"); int n = context.getContentResolver().delete(fileUri, null, null); if (n > 0) { LOG.debug("Deleted from Files provider: " + fileUri); } Field mNoMediaF = mClient.getClass().getDeclaredField("mNoMedia"); mNoMediaF.setAccessible(true); mNoMediaF.setBoolean(mClient, false); // This is only for HTC (tested only on HTC One M8) try { Field mFileCacheF = clazz.getDeclaredField("mFileCache"); mFileCacheF.setAccessible(true); mFileCacheF.set(scanner, new HashMap<String, Object>()); } catch (Throwable e) { // no an HTC, I need some time to refactor this hack } Method doScanFileM = mClient.getClass().getDeclaredMethod("doScanFile", String.class, String.class, long.class, long.class, boolean.class, boolean.class, boolean.class); Uri mediaUri = (Uri) doScanFileM.invoke(mClient, f.getAbsolutePath(), null, f.lastModified(), f.length(), false, true, false); Method releaseM = clazz.getDeclaredMethod("release"); releaseM.invoke(scanner); return mediaUri; } catch (Throwable e) { e.printStackTrace(); return null; } }
From source file:io.tempra.AppServer.java
/** * Adds the specified path to the java library path * * @param pathToAdd//from w ww. j a va2 s . c om * the path to add * @throws Exception */ public static void addLibraryPath(String pathToAdd) throws Exception { final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths"); usrPathsField.setAccessible(true); // get array of paths final String[] paths = (String[]) usrPathsField.get(null); // check if the path to add is already present for (String path : paths) { if (path.equals(pathToAdd)) { return; } } // add the new path final String[] newPaths = Arrays.copyOf(paths, paths.length + 1); newPaths[newPaths.length - 1] = pathToAdd; usrPathsField.set(null, newPaths); }
From source file:com.psiphon3.psiphonlibrary.WebViewProxySettings.java
@TargetApi(Build.VERSION_CODES.KITKAT) @SuppressWarnings("rawtypes") private static boolean setWebkitProxyKitKat(Context appContext, String host, int port) { System.setProperty("http.proxyHost", host); System.setProperty("http.proxyPort", port + ""); System.setProperty("https.proxyHost", host); System.setProperty("https.proxyPort", port + ""); try {/*from w ww . j ava 2 s .c o m*/ Class applicationClass = Class.forName("android.app.Application"); Field loadedApkField = applicationClass.getDeclaredField("mLoadedApk"); loadedApkField.setAccessible(true); Object loadedApk = loadedApkField.get(appContext); Class loadedApkClass = Class.forName("android.app.LoadedApk"); Field receiversField = loadedApkClass.getDeclaredField("mReceivers"); receiversField.setAccessible(true); ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk); for (Object receiverMap : receivers.values()) { for (Object receiver : ((ArrayMap) receiverMap).keySet()) { Class receiverClass = receiver.getClass(); if (receiverClass.getName().contains("ProxyChangeListener")) { Method onReceiveMethod = receiverClass.getDeclaredMethod("onReceive", Context.class, Intent.class); Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); final String CLASS_NAME = "android.net.ProxyProperties"; Class proxyPropertiesClass = Class.forName(CLASS_NAME); Constructor constructor = proxyPropertiesClass.getConstructor(String.class, Integer.TYPE, String.class); constructor.setAccessible(true); Object proxyProperties = constructor.newInstance(host, port, null); intent.putExtra("proxy", (Parcelable) proxyProperties); onReceiveMethod.invoke(receiver, appContext, intent); } } } return true; } catch (ClassNotFoundException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (NoSuchFieldException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (IllegalAccessException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (IllegalArgumentException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (NoSuchMethodException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (InvocationTargetException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (InstantiationException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } return false; }
From source file:Main.java
public static Collection<Field> getDeepDeclaredFields(Class<?> c) { if (_reflectedFields.containsKey(c)) { return _reflectedFields.get(c); }//from ww w. j av a2 s . co m Collection<Field> fields = new ArrayList<Field>(); Class<?> curr = c; while (curr != null) { try { Field[] local = curr.getDeclaredFields(); for (Field field : local) { if (!field.isAccessible()) { try { field.setAccessible(true); } catch (Exception ignored) { } } int modifiers = field.getModifiers(); if (!Modifier.isStatic(modifiers) && !field.getName().startsWith("this$") && !Modifier.isTransient(modifiers)) { fields.add(field); } } } catch (ThreadDeath t) { throw t; } catch (Throwable ignored) { } curr = curr.getSuperclass(); } _reflectedFields.put(c, fields); return fields; }
From source file:com.amazonaws.retry.RetryPolicyTestBase.java
public static void injectMockHttpClient(AmazonHttpClient amazonHttpClient, HttpClient mockHttpClient) { try {//from w ww. java2 s . c o m Field f = AmazonHttpClient.class.getDeclaredField("httpClient"); f.setAccessible(true); f.set(amazonHttpClient, mockHttpClient); } catch (Exception e) { Assert.fail("Cannot inject the mock HttpClient object. " + e.getMessage()); } }