Java Code Examples for java.lang.reflect.Method.setAccessible()

The following are Jave code examples for showing how to use setAccessible() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: renderscript_examples   File: RenderScriptHolder.java   View Source Code Vote up 6 votes
private Method getRSScriptCCreateMethod() {
    if (nScriptCCreate == null)

        try {
            Method method = RenderScript.class.getDeclaredMethod("nScriptCCreate", String.class, String.class, byte[].class, int.class);
            method.setAccessible(true);

            nScriptCCreate = method;

            return method;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("nScriptCCreate method does not exists");
        }

    return nScriptCCreate;
}
 
Example 2
Project: SelectName   File: Utils.java   View Source Code Vote up 6 votes
/**
 * Calling the convertToTranslucent method on platforms before Android 5.0
 */
public static void convertActivityToTranslucentBeforeL(Activity activity) {
    try {
        Class<?>[] classes = Activity.class.getDeclaredClasses();
        Class<?> translucentConversionListenerClazz = null;
        for (Class clazz : classes) {
            if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
                translucentConversionListenerClazz = clazz;
            }
        }
        Method method = Activity.class.getDeclaredMethod("convertToTranslucent",
                translucentConversionListenerClazz);
        method.setAccessible(true);
        method.invoke(activity, new Object[] {
            null
        });
    } catch (Throwable t) {
    }
}
 
Example 3
Project: DroidPlugin   File: MethodUtils.java   View Source Code Vote up 6 votes
public static Method getAccessibleMethod(final Class<?> cls, final String methodName,
                                         final Class<?>... parameterTypes) throws NoSuchMethodException {
    String key = getKey(cls, methodName, parameterTypes);
    Method method;
    synchronized (sMethodCache) {
        method = sMethodCache.get(key);
    }
    if (method != null) {
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        return method;
    }

    Method accessibleMethod = getAccessibleMethod(cls.getMethod(methodName,
            parameterTypes));
    synchronized (sMethodCache) {
        sMethodCache.put(key, accessibleMethod);
    }
    return accessibleMethod;

}
 
Example 4
Project: openjdk-jdk10   File: bug7143614.java   View Source Code Vote up 6 votes
private static void validate() throws Exception {
    Method getSelectedUIMethod = SynthLookAndFeel.class.getDeclaredMethod("getSelectedUI");

    getSelectedUIMethod.setAccessible(true);

    Method getSelectedUIStateMethod = SynthLookAndFeel.class.getDeclaredMethod("getSelectedUIState");

    getSelectedUIStateMethod.setAccessible(true);

    if (getSelectedUIMethod.invoke(null) != componentUI) {
        throw new RuntimeException("getSelectedUI returns invalid value");
    }
    if (((Integer) getSelectedUIStateMethod.invoke(null)).intValue() !=
            (SynthConstants.SELECTED | SynthConstants.FOCUSED)) {
        throw new RuntimeException("getSelectedUIState returns invalid value");
    }

}
 
Example 5
Project: AndHook   File: AndHook.java   View Source Code Vote up 6 votes
public static Method findMethodHierarchically(final Class<?> clazz,
                                              final String name, final Class<?>... parameterTypes) {
    Method m = null;
    Class<?> c = clazz;
    do {
        try {
            m = c.getDeclaredMethod(name, parameterTypes);
        } catch (final NoSuchMethodException e) {
            c = c.getSuperclass();
            if (c == null)
                break;
        }
    } while (m == null);
    if (m != null) {
        m.setAccessible(true);
    } else {
        Log.e(AndHook.LOG_TAG, "failed to find method " + name
                + " of class " + clazz.getName());
    }
    return m;
}
 
Example 6
Project: com.zsmartsystems.zigbee   File: EmberFirmwareUpdateHandlerTest.java   View Source Code Vote up 6 votes
private boolean getBlPrompt(String packet) {
    ByteArrayInputStream stream = new ByteArrayInputStream(packet.getBytes());
    ZigBeePort port = new TestPort(stream);
    EmberFirmwareUpdateHandler firmwareHandler = new EmberFirmwareUpdateHandler(null, null, port, null);

    Method privateMethod;
    try {
        privateMethod = EmberFirmwareUpdateHandler.class.getDeclaredMethod("getBlPrompt");
        privateMethod.setAccessible(true);

        return (boolean) privateMethod.invoke(firmwareHandler);
    } catch (NoSuchMethodException | SecurityException | IllegalArgumentException | IllegalAccessException
            | InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return false;
}
 
Example 7
Project: Liz   File: ThemeHelper.java   View Source Code Vote up 6 votes
public void setScrollViewColor(ScrollView scr){
	try
	{
		Field mScrollCacheField = View.class.getDeclaredField("mScrollCache");
		mScrollCacheField.setAccessible(true);
		Object mScrollCache = mScrollCacheField.get(scr); // scr is your Scroll View

		Field scrollBarField = mScrollCache.getClass().getDeclaredField("scrollBar");
		scrollBarField.setAccessible(true);
		Object scrollBar = scrollBarField.get(mScrollCache);

		Method method = scrollBar.getClass().getDeclaredMethod("setVerticalThumbDrawable", Drawable.class);
		method.setAccessible(true);

		ColorDrawable ColorDraw = new ColorDrawable(getPrimaryColor());
		method.invoke(scrollBar, ColorDraw);
	} catch(Exception e) {
		e.printStackTrace();
	}
}
 
Example 8
Project: memory   File: AllocateDirectWritableMap.java   View Source Code Vote up 5 votes
@Override
public void force() {
  try {
    final Method method = MappedByteBuffer.class.getDeclaredMethod("force0",
            FileDescriptor.class, long.class, long.class);
    method.setAccessible(true);
    method.invoke(super.state.getMappedByteBuffer(), super.state.getRandomAccessFile().getFD(),
            super.state.getNativeBaseOffset(), super.state.getCapacity());
  } catch (final Exception e) {
    throw new RuntimeException(String.format("Encountered %s exception in force", e.getClass()));
  }
}
 
Example 9
Project: AstralEdit   File: ReflectionUtils.java   View Source Code Vote up 5 votes
/**
 * Invokes the static method of the given clazz, name, paramTypes, params
 *
 * @param clazz      clazz
 * @param name       name
 * @param paramTypes paramTypes
 * @param params     params
 * @param <T>        returnType
 * @return returnValue
 * @throws NoSuchMethodException     exception
 * @throws InvocationTargetException exception
 * @throws IllegalAccessException    exception
 */
public static <T> T invokeMethodByClass(Class<?> clazz, String name, Class<?>[] paramTypes, Object[] params) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    if (clazz == null)
        throw new IllegalArgumentException("Class cannot be null!");
    if (name == null)
        throw new IllegalArgumentException("Name cannot be null!");
    if (paramTypes == null)
        throw new IllegalArgumentException("ParamTypes cannot be null");
    if (params == null)
        throw new IllegalArgumentException("Params cannot be null!");
    final Method method = clazz.getDeclaredMethod(name, paramTypes);
    method.setAccessible(true);
    return (T) method.invoke(null, params);
}
 
Example 10
Project: VirtualAPK   File: ReflectUtil.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public static Object invoke(Class clazz, Object target, String name, Object... args)
        throws Exception {
    Class[] parameterTypes = null;
    if (args != null) {
        parameterTypes = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            parameterTypes[i] = args[i].getClass();
        }
    }

    Method method = clazz.getDeclaredMethod(name, parameterTypes);
    method.setAccessible(true);
    return method.invoke(target, args);
}
 
Example 11
Project: marathonv5   File: BeanToJsonConverter.java   View Source Code Vote up 5 votes
private Object mapObject(Object toConvert, int maxDepth, boolean skipNulls) throws Exception {
    if (maxDepth < 1) {
        return null;
    }

    // Raw object via reflection? Nope, not needed
    JSONObject mapped = new JSONObject();
    for (SimplePropertyDescriptor pd : SimplePropertyDescriptor.getPropertyDescriptors(toConvert.getClass())) {
        if ("class".equals(pd.getName())) {
            mapped.put("class", toConvert.getClass().getName());
            continue;
        }

        Method readMethod = pd.getReadMethod();
        if (readMethod == null) {
            continue;
        }

        if (readMethod.getParameterTypes().length > 0) {
            continue;
        }

        readMethod.setAccessible(true);

        Object result = readMethod.invoke(toConvert);
        result = convertObject(result, maxDepth - 1);
        if (!skipNulls || result != JSONObject.NULL) {
            mapped.put(pd.getName(), result);
        }
    }

    return mapped;
}
 
Example 12
Project: openjdk-jdk10   File: LocalLongHelper.java   View Source Code Vote up 5 votes
private static void setupReflectionStatics() throws Throwable {
    Class<?> liveStackFrameClass = Class.forName("java.lang.LiveStackFrame");
    primitiveValueClass = Class.forName("java.lang.LiveStackFrame$PrimitiveSlot");

    getLocals = liveStackFrameClass.getDeclaredMethod("getLocals");
    getLocals.setAccessible(true);

    longValue = primitiveValueClass.getDeclaredMethod("longValue");
    longValue.setAccessible(true);

    Class<?> stackFrameInfoClass = Class.forName("java.lang.StackFrameInfo");
    memberName = stackFrameInfoClass.getDeclaredField("memberName");
    memberName.setAccessible(true);
    offset = stackFrameInfoClass.getDeclaredField("bci");
    offset.setAccessible(true);
    getMethodType = Class.forName("java.lang.invoke.MemberName").getDeclaredMethod("getMethodType");
    getMethodType.setAccessible(true);

    Class<?> extendedOptionClass = Class.forName("java.lang.StackWalker$ExtendedOption");
    Method ewsNI = StackWalker.class.getDeclaredMethod("newInstance", Set.class, extendedOptionClass);
    ewsNI.setAccessible(true);
    Field f = extendedOptionClass.getDeclaredField("LOCALS_AND_OPERANDS");
    f.setAccessible(true);
    Object localsAndOperandsOption = f.get(null);

    primitiveSize = primitiveValueClass.getDeclaredMethod("size");
    primitiveSize.setAccessible(true);
    sw = (StackWalker) ewsNI.invoke(null, java.util.Collections.emptySet(), localsAndOperandsOption);
}
 
Example 13
Project: ProjectAres   File: ReflectiveProperty.java   View Source Code Vote up 5 votes
public static ReflectiveProperty of(Method method, Inspectable.Inspect annotation) {
    if(method.getParameterTypes().length > 0) {
        throw new IllegalArgumentException("Can't inspect a method with parameters");
    }

    method.setAccessible(true);
    return new ReflectiveProperty(
        annotation.name().length() > 0 ? annotation.name()
                                       : Methods.removeBeanPrefix(method.getName()),
        TypeToken.of(method.getGenericReturnType()),
        new Inspection(annotation),
        MethodHandleUtils.privateUnreflect(method)
    );
}
 
Example 14
Project: FlexMC   File: LibraryManager.java   View Source Code Vote up 5 votes
private void loadJarToClassPath( File file ) throws IOException {
    URL url = file.toURI().toURL();
    ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
    try {
        Method method = URLClassLoader.class.getDeclaredMethod( "addURL", URL.class );
        if( !method.isAccessible() ) {
            method.setAccessible( true );
        }
        method.invoke( systemClassLoader, url );
    } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e ) {
        throw new RuntimeException( e );
    }
}
 
Example 15
Project: dremio-oss   File: ShimLoader.java   View Source Code Vote up 5 votes
private static Class<?> injectNativeLoader() {
  try {
    ClassLoader e = getRootClassLoader();
    byte[] libLoaderByteCode = getByteCode("/com/mapr/fs/shim/LibraryLoader.bytecode");
    ArrayList preloadClassByteCode = new ArrayList(PRELOAD_CLASSES.length);
    String[] classLoader = PRELOAD_CLASSES;
    int defineClass = classLoader.length;

    for(int pd = 0; pd < defineClass; ++pd) {
      String ex = classLoader[pd];
      preloadClassByteCode.add(getByteCode(String.format("/%s.class", new Object[]{ex.replaceAll("\\.", "/")})));
    }

    Class var15 = Class.forName("java.lang.ClassLoader");
    Method var16 = var15.getDeclaredMethod("defineClass", new Class[]{String.class, byte[].class, Integer.TYPE, Integer.TYPE, ProtectionDomain.class});
    ProtectionDomain var17 = System.class.getProtectionDomain();
    var16.setAccessible(true);

    try {
      trace("injectNativeLoader: Loading MapR native classes", new Object[0]);
      var16.invoke(e, new Object[]{"com.mapr.fs.shim.LibraryLoader", libLoaderByteCode, Integer.valueOf(0), Integer.valueOf(libLoaderByteCode.length), var17});

      for(int var18 = 0; var18 < PRELOAD_CLASSES.length; ++var18) {
        byte[] b = (byte[])preloadClassByteCode.get(var18);
        var16.invoke(e, new Object[]{PRELOAD_CLASSES[var18], b, Integer.valueOf(0), Integer.valueOf(b.length), var17});
      }
    } catch (InvocationTargetException var12) {
      throw var12;
    } finally {
      var16.setAccessible(false);
    }

    return e.loadClass("com.mapr.fs.shim.LibraryLoader");
  } catch (Exception var14) {
    var14.printStackTrace(System.err);
    throw new RuntimeException("Failure loading MapRClient. ", var14);
  }
}
 
Example 16
Project: openjdk-jdk10   File: FontDisposeTest.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception
{
    // The bug only happens with Type 1 fonts. The Ghostscript font files
    // should be commonly available. From distro pacakge or
    //  ftp://ftp.gnu.org/gnu/ghostscript/gnu-gs-fonts-other-6.0.tar.gz
    // Pass pfa/pfb font file as argument
    String path = args[0];

    // Load
    InputStream stream = new FileInputStream(path);
    Font font = Font.createFont(Font.TYPE1_FONT,stream);

    // Ensure native bits have been generated
    BufferedImage img = new BufferedImage(100,100,
                             BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();
    FontRenderContext frc = g2d.getFontRenderContext();

    font.getLineMetrics("derp",frc);

    // Force disposal -
    // System.gc() is not sufficient.
    Field font2DHandleField = Font.class.getDeclaredField("font2DHandle");
    font2DHandleField.setAccessible(true);
    sun.font.Font2DHandle font2DHandle =
                  (sun.font.Font2DHandle)font2DHandleField.get(font);

    sun.font.Font2D font2D = font2DHandle.font2D;
    sun.font.Type1Font type1Font = (sun.font.Type1Font)font2D;

    Method getScalerMethod =
    sun.font.Type1Font.class.getDeclaredMethod("getScaler");
    getScalerMethod.setAccessible(true);
    sun.font.FontScaler scaler =
              (sun.font.FontScaler)getScalerMethod.invoke(type1Font);

    // dispose should not crash due to double free
    scaler.dispose();
}
 
Example 17
Project: jdk8u-jdk   File: ReflectionFactory.java   View Source Code Vote up 5 votes
/**
 * Returns a direct MethodHandle for the {@code writeReplace} method on
 * a serializable class.
 * The single argument of {@link MethodHandle#invoke} is the serializable
 * object.
 *
 * @param cl the Serializable class
 * @return  a direct MethodHandle for the {@code writeReplace} method of the class or
 *          {@code null} if the class does not have a {@code writeReplace} method
 */
private MethodHandle getReplaceResolveForSerialization(Class<?> cl,
                                                       String methodName) {
    if (!Serializable.class.isAssignableFrom(cl)) {
        return null;
    }

    Class<?> defCl = cl;
    while (defCl != null) {
        try {
            Method m = defCl.getDeclaredMethod(methodName);
            if (m.getReturnType() != Object.class) {
                return null;
            }
            int mods = m.getModifiers();
            if (Modifier.isStatic(mods) | Modifier.isAbstract(mods)) {
                return null;
            } else if (Modifier.isPublic(mods) | Modifier.isProtected(mods)) {
                // fall through
            } else if (Modifier.isPrivate(mods) && (cl != defCl)) {
                return null;
            } else if (!packageEquals(cl, defCl)) {
                return null;
            }
            try {
                // Normal return
                m.setAccessible(true);
                return MethodHandles.lookup().unreflect(m);
            } catch (IllegalAccessException ex0) {
                // setAccessible should prevent IAE
                throw new InternalError("Error", ex0);
            }
        } catch (NoSuchMethodException ex) {
            defCl = defCl.getSuperclass();
        }
    }
    return null;
}
 
Example 18
Project: openjdk-jdk10   File: TestSerializedLambdaNameStability.java   View Source Code Vote up 4 votes
Method getMethod(Class<?> k, String name, Class<?> argTypes) throws Exception {
    Method meth = k.getDeclaredMethod(name, argTypes);
    meth.setAccessible(true);
    return meth;
}
 
Example 19
Project: PointCloudCrust   File: PointCloudCrustImplTest.java   View Source Code Vote up 4 votes
/**
 * Helper method for calling the triangleCenter method.
 */
private Vector callTriangleCenter(Vector[] triangle) throws Exception {
    Method method = PointCloudCrustImpl.class.getDeclaredMethod("triangleCenter", Vector[].class);
    method.setAccessible(true);
    return (Vector) method.invoke(pointCloudCrust, new Object[]{triangle});
}
 
Example 20
Project: Leanplum-Android-SDK   File: SocketIOClientTest.java   View Source Code Vote up 4 votes
/**
 * Test for {@link SocketIOClient#userAgentString()} that should return user-agent.
 *
 * @throws Exception
 */
@Test
public void testUserAgentString() throws Exception {
  mockStatic(Util.class);
  mockStatic(Request.class);
  spy(Leanplum.class);
  SocketIOClient socketIOClient = new SocketIOClient(new URI(""), new SocketIOClient.Handler() {
    @Override
    public void onConnect() {

    }

    @Override
    public void on(String event, JSONArray arguments) {

    }

    @Override
    public void onDisconnect(int code, String reason) {

    }

    @Override
    public void onError(Exception error) {

    }
  });
  Method userAgentStringMethod = SocketIOClient.class.getDeclaredMethod("userAgentString");
  userAgentStringMethod.setAccessible(true);
  assertNotNull(userAgentStringMethod);
  Constants.LEANPLUM_VERSION = "1";
  Constants.CLIENT = "android";
  when(Request.class, "appId").thenReturn("app_id");
  when(Util.class, "getVersionName").thenReturn("app_version");
  when(Util.class, "getApplicationName", Matchers.any(Context.class)).thenReturn("app_name");

  // Test with a non-null Context.
  doReturn(RuntimeEnvironment.application).when(Leanplum.class, "getContext");
  assertEquals("app_name/app_version(app_id; android; 1/s)",
      (String) userAgentStringMethod.invoke(socketIOClient));

  // Test with a null Context.
  doReturn(null).when(Leanplum.class, "getContext");
  assertEquals("websocket(app_id; android; 1/s)",
      (String) userAgentStringMethod.invoke(socketIOClient));
}