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

The following examples show how to use java.lang.reflect.Method#setAccessible() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UnsafeThreadLocal.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private static Object invokePrivate(Object object, String methodName,
    Class[] argTypes, Object[] args) throws SecurityException,
    NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
    InvocationTargetException {

  Method method = null;
  Class clazz = object.getClass();
  while (method == null) {
    try {
      method = clazz.getDeclaredMethod(methodName, argTypes);
    } catch (NoSuchMethodException e) {
      clazz = clazz.getSuperclass();
      if (clazz == null) {
        throw e;
      }
    }
  }
  method.setAccessible(true);
  Object result = method.invoke(object, args);
  return result;
}
 
Example 2
Source File: ArtHook.java    From ArtHook with Apache License 2.0 6 votes vote down vote up
public static OriginalMethod hook(Object originalMethod, Method replacementMethod, String backupIdentifier) {
    ArtMethod backArt;
    if (originalMethod instanceof Method) {
        backArt = hook((Method) originalMethod, replacementMethod);
    } else if (originalMethod instanceof Constructor) {
        backArt = hook((Constructor<?>) originalMethod, replacementMethod);
        backArt.convertToMethod();
    } else {
        throw new RuntimeException("original method must be of type Method or Constructor");
    }

    Method backupMethod = (Method) backArt.getAssociatedMethod();
    backupMethod.setAccessible(true);
    OriginalMethod.store(originalMethod, backupMethod, backupIdentifier);

    return new OriginalMethod(backupMethod);
}
 
Example 3
Source File: NetworkUtil.java    From Android-Application-ZJB with Apache License 2.0 5 votes vote down vote up
public static boolean isMobileEnabled(Context context) {
    try {
        Method e = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled", new Class[0]);
        e.setAccessible(true);
        return ((Boolean) e.invoke(getConnManager(context), new Object[0])).booleanValue();
    } catch (Exception var2) {
        var2.printStackTrace();
        return true;
    }
}
 
Example 4
Source File: InitializerTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoggingWithPublish() throws Exception {

    File log4jFile = createLog4jFile(LOG4J_CONFIG1);
    try {
        // Set path of log4j properties
        log4jFolderPath = log4jFile.getParentFile().getParent();
        setSysSetting(log4jFolderPath);

        // Delete temp file again
        log4jFile.delete();

        assertFalse(log4jFile.exists());

        // Invoke "private" method :)
        // => publish template file
        Method method = testElm.getClass().getDeclaredMethod(
                "postConstruct");
        method.setAccessible(true);
        method.invoke(testElm);

        assertTrue(log4jFile.exists());

    } finally {
        log4jFile.delete();
        resetSysSetting();
    }

}
 
Example 5
Source File: AuthorizerFactory.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private void performMethodInjection(final Object instance, final Class authorizerClass) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    for (final Method method : authorizerClass.getMethods()) {
        if (method.isAnnotationPresent(AuthorizerContext.class)) {
            // make the method accessible
            final boolean isAccessible = method.isAccessible();
            method.setAccessible(true);

            try {
                final Class<?>[] argumentTypes = method.getParameterTypes();

                // look for setters (single argument)
                if (argumentTypes.length == 1) {
                    final Class<?> argumentType = argumentTypes[0];

                    // look for well known types
                    if (NiFiRegistryProperties.class.isAssignableFrom(argumentType)) {
                        // nifi properties injection
                        method.invoke(instance, properties);
                    }
                }
            } finally {
                method.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = authorizerClass.getSuperclass();
    if (parentClass != null && Authorizer.class.isAssignableFrom(parentClass)) {
        performMethodInjection(instance, parentClass);
    }
}
 
Example 6
Source File: UpdateDownloader.java    From SkinsRestorerX with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the plugin's file name
 *
 * @return the plugin file name
 */
public File getPluginFile() {
    if (!(plugin instanceof JavaPlugin)) {
        return null;
    }
    try {
        Method method = JavaPlugin.class.getDeclaredMethod("getFile");
        method.setAccessible(true);
        return (File) method.invoke(plugin);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException("Could not get plugin file", e);
    }
}
 
Example 7
Source File: PreferenceListFragment.java    From android_dbinspector with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the root of the preference hierarchy that this activity is showing.
 *
 * @return The {@link PreferenceScreen} that is the root of the preference hierarchy.
 */
public PreferenceScreen getPreferenceScreen() {
    try {
        Method m = PreferenceManager.class.getDeclaredMethod("getPreferenceScreen");
        m.setAccessible(true);
        return (PreferenceScreen) m.invoke(mPreferenceManager);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 8
Source File: PreferenceManagerCompat.java    From android-support-v4-preferencefragment with Apache License 2.0 5 votes vote down vote up
/**
    * Sets the root of the preference hierarchy.
    * 
    * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
    * @return Whether the {@link PreferenceScreen} given is different than the previous. 
    */
static boolean setPreferences(PreferenceManager manager, PreferenceScreen screen) {
	try {
		Method m = PreferenceManager.class.getDeclaredMethod("setPreferences", PreferenceScreen.class);
		m.setAccessible(true);
		return ((Boolean) m.invoke(manager, screen));
	} catch (Exception e) {
		Log.w(TAG, "Couldn't call PreferenceManager.setPreferences by reflection", e);
	}
	return false;
}
 
Example 9
Source File: MusicActivity.java    From LLApp with Apache License 2.0 5 votes vote down vote up
/**
 * 这个方法用来解决超出的menuItem不显示图标的问题,这个方法在AppCompatActivity中不被调用
 * @param featureId
 * @param menu
 * @return
 */
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
        if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
            try {
                Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                m.setAccessible(true);
                m.invoke(menu, true);
            } catch (Exception e) {
            }
        }
    }
    return super.onMenuOpened(featureId, menu);
}
 
Example 10
Source File: FlinkKafkaInternalProducer.java    From flink with Apache License 2.0 5 votes vote down vote up
private static Object invoke(Object object, String methodName, Class<?>[] argTypes, Object[] args) {
	try {
		Method method = object.getClass().getDeclaredMethod(methodName, argTypes);
		method.setAccessible(true);
		return method.invoke(object, args);
	} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
		throw new RuntimeException("Incompatible KafkaProducer version", e);
	}
}
 
Example 11
Source File: SwitchLookup.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<String> computePaths(MimePath mimePath, String prefixPath, String suffixPath) {
    try {
        Method m = MimePath.class.getDeclaredMethod("getInheritedPaths", String.class, String.class); //NOI18N
        m.setAccessible(true);
        @SuppressWarnings("unchecked")
        List<String> paths = (List<String>) m.invoke(mimePath, prefixPath, suffixPath);
        return paths;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "Can't call org.netbeans.api.editor.mimelookup.MimePath.getInheritedPaths method.", e); //NOI18N
    }
    
    // No inherited mimepaths, provide at least something
    StringBuilder sb = new StringBuilder();
    if (prefixPath != null && prefixPath.length() > 0) {
        sb.append(prefixPath);
    }
    if (mimePath.size() > 0) {
        if (sb.length() > 0) {
            sb.append('/'); //NOI18N
        }
        sb.append(mimePath.getPath());
    }
    if (suffixPath != null && suffixPath.length() > 0) {
        if (sb.length() > 0) {
            sb.append('/'); //NOI18N
        }
        sb.append(suffixPath);
    }
    return Collections.singletonList(sb.toString());
}
 
Example 12
Source File: Reflection.java    From giffun with Apache License 2.0 5 votes vote down vote up
/**
 * This method use java reflect API to execute method dynamically. Most
 * importantly, it could access the methods with private modifier to break
 * encapsulation.
 *
 * @param object         The object to invoke method.
 * @param methodName     The method name to invoke.
 * @param parameters     The parameters.
 * @param objectClass    Use objectClass to find method to invoke.
 * @param parameterTypes The parameter types.
 * @return Returns the result of dynamically invoking method.
 */
public static Object send(Object object, String methodName, Object[] parameters, Class<?> objectClass,
                          Class<?>[] parameterTypes) throws SecurityException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (parameters == null) {
        parameters = new Object[]{};
    }
    if (parameterTypes == null) {
        parameterTypes = new Class[]{};
    }
    Method method = objectClass.getDeclaredMethod(methodName, parameterTypes);
    method.setAccessible(true);
    return method.invoke(object, parameters);
}
 
Example 13
Source File: PreferencesListFragment.java    From Linphone4Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the root of the preference hierarchy that this activity is showing.
 * 
 * @return The {@link PreferenceScreen} that is the root of the preference
 *         hierarchy.
 */
public PreferenceScreen getPreferenceScreen() {
    try {
        Method m = PreferenceManager.class.getDeclaredMethod("getPreferenceScreen");
        m.setAccessible(true);
        return (PreferenceScreen) m.invoke(mPreferenceManager);
    } catch(Exception e) {
        Log.e("[PreferencesListFragment] getPreferenceScreen " + e);
    }
    
    return null;
}
 
Example 14
Source File: TestPigServer.java    From spork with Apache License 2.0 5 votes vote down vote up
private static void registerNewResource(String file) throws Exception {
    URL urlToAdd = new File(file).toURI().toURL();
    URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method addMethod = URLClassLoader.class.
            getDeclaredMethod("addURL", new Class[]{URL.class});
    addMethod.setAccessible(true);
    addMethod.invoke(sysLoader, new Object[]{urlToAdd});
}
 
Example 15
Source File: MultiResolutionImageTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static Method getScalableImageMethod(String name,
        Class... parameterTypes) throws Exception {
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Method method = toolkit.getClass().getDeclaredMethod(name, parameterTypes);
    method.setAccessible(true);
    return method;
}
 
Example 16
Source File: CompensationContext.java    From txle with Apache License 2.0 4 votes vote down vote up
public void addCompensationContext(Method compensationMethod, Object target) {
  compensationMethod.setAccessible(true);
  contexts.put(compensationMethod.toString(), new CompensationContextInternal(target, compensationMethod));
}
 
Example 17
Source File: PDI4910_DenormaliserTest.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeNormalise() throws Exception {

  // init step data
  DenormaliserData stepData = new DenormaliserData();
  stepData.keyFieldNr = 0;
  stepData.keyValue = new HashMap<String, List<Integer>>();
  stepData.keyValue.put( "1", Arrays.asList( new Integer[] { 0, 1 } ) );
  stepData.fieldNameIndex = new int[] { 1, 2 };
  stepData.inputRowMeta = new RowMeta();
  ValueMetaDate outDateField1 = new ValueMetaDate( "date_field[yyyy-MM-dd]" );
  ValueMetaDate outDateField2 = new ValueMetaDate( "date_field[yyyy/MM/dd]" );
  stepData.outputRowMeta = new RowMeta();
  stepData.outputRowMeta.addValueMeta( 0, outDateField1 );
  stepData.outputRowMeta.addValueMeta( 1, outDateField2 );
  stepData.removeNrs = new int[] { };
  stepData.targetResult = new Object[] { null, null };

  // init step meta
  DenormaliserMeta stepMeta = new DenormaliserMeta();
  DenormaliserTargetField[] denormaliserTargetFields = new DenormaliserTargetField[ 2 ];
  DenormaliserTargetField targetField1 = new DenormaliserTargetField();
  DenormaliserTargetField targetField2 = new DenormaliserTargetField();
  targetField1.setTargetFormat( "yyyy-MM-dd" );
  targetField2.setTargetFormat( "yyyy/MM/dd" );
  denormaliserTargetFields[ 0 ] = targetField1;
  denormaliserTargetFields[ 1 ] = targetField2;
  stepMeta.setDenormaliserTargetField( denormaliserTargetFields );

  // init row meta
  RowMetaInterface rowMeta = new RowMeta();
  rowMeta.addValueMeta( 0, new ValueMetaInteger( "key" ) );
  rowMeta.addValueMeta( 1, new ValueMetaString( "stringDate1" ) );
  rowMeta.addValueMeta( 2, new ValueMetaString( "stringDate2" ) );

  // init row data
  Object[] rowData = new Object[] { 1L, "2000-10-20", "2000/10/20" };

  // init step
  denormaliser = new Denormaliser( mockHelper.stepMeta, stepData,
    0, mockHelper.transMeta, mockHelper.trans );

  // inject step meta
  Field metaField = denormaliser.getClass().getDeclaredField( "meta" );
  Assert.assertNotNull( "Can't find a field 'meta' in class Denormalizer", metaField );
  metaField.setAccessible( true );
  metaField.set( denormaliser, stepMeta );

  // call tested method
  Method deNormalise =
    denormaliser.getClass().getDeclaredMethod( "deNormalise", RowMetaInterface.class, Object[].class );
  Assert.assertNotNull( "Can't find a method 'deNormalise' in class Denormalizer", deNormalise );
  deNormalise.setAccessible( true );
  deNormalise.invoke( denormaliser, rowMeta, rowData );

  // vefiry
  for ( Object res : stepData.targetResult ) {
    Assert.assertNotNull( "Date is null", res );
  }
}
 
Example 18
Source File: BleConnectionCompat.java    From RxAndroidBle with Apache License 2.0 4 votes vote down vote up
private static Method getMethodFromClass(Class<?> cls, String methodName) throws NoSuchMethodException {
    Method method = cls.getDeclaredMethod(methodName);
    method.setAccessible(true);
    return method;
}
 
Example 19
Source File: NavigatorPanelWithToolbarTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testFix217212_ActivatePanel() throws Exception {
    InstanceContent ic = new InstanceContent();
    GlobalLookup4TestImpl nodesLkp = new GlobalLookup4TestImpl(ic);
    UnitTestUtils.prepareTest(new String[]{
                "/META-INF/generated-layer.xml"},
            Lookups.singleton(nodesLkp));

    TestLookupHint hint = new TestLookupHint("annotation/tester");
    ic.add(hint);

    final NavigatorTC navTC = NavigatorTC.getInstance();
    Field field = NavigatorController.class.getDeclaredField("updateWhenNotShown");
    field.setAccessible(true);
    field.setBoolean(navTC.getController(), true);
    try {
        Mutex.EVENT.readAccess(new Mutex.ExceptionAction() {
            @Override
            public Object run() throws Exception {
                navTC.getController().propertyChange(
                        new PropertyChangeEvent(navTC, TopComponent.Registry.PROP_TC_OPENED, null, navTC));
                return null;
            }
        });
        waitForProviders(navTC);
        NavigatorPanel selPanel = navTC.getSelectedPanel();
        assertNotNull("Selected panel is null", selPanel);

        List<? extends NavigatorPanel> panels = navTC.getPanels();
        assertEquals(2, panels.size());

        NavigatorPanel lazyPanel1 = panels.get(0);
        Method method = LazyPanel.class.getDeclaredMethod("initialize");
        method.setAccessible(true);
        NavigatorPanel delegate1 = (NavigatorPanel) method.invoke(lazyPanel1);

        NavigatorPanel lazyPanel2 = panels.get(1);
        method = LazyPanel.class.getDeclaredMethod("initialize");
        method.setAccessible(true);
        NavigatorPanel delegate2 = (NavigatorPanel) method.invoke(lazyPanel2);

        System.out.println("selected panel before: " + selPanel.getDisplayName());

        //find not-selected panel
        final NavigatorPanel toActivate;
        final NavigatorPanel toActivateLazy;
        if (selPanel.equals(lazyPanel1)) {
            toActivate = delegate2;
            toActivateLazy = lazyPanel2;
        } else {
            toActivate = delegate1;
            toActivateLazy = lazyPanel1;

        }

        Mutex.EVENT.readAccess(new Mutex.ExceptionAction() {
            @Override
            public Object run() throws Exception {
                NavigatorHandler.activatePanel(toActivate);
                return null;
            }
        });

        assertTrue(selPanel != navTC.getSelectedPanel());
        assertTrue(toActivateLazy == navTC.getSelectedPanel());

        System.out.println("selected panel after: " + navTC.getSelectedPanel().getDisplayName());
    } finally {
        navTC.getController().propertyChange(
                new PropertyChangeEvent(navTC, TopComponent.Registry.PROP_TC_CLOSED, null, navTC));
    }
}
 
Example 20
Source File: Xsd2UmlTweakerVisitorTest.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransform() throws Exception {
    Method method = visitor.getClass().getDeclaredMethod("transform", ClassType.class, ModelIndex.class);
    method.setAccessible(true);
    ClassType classType = Mockito.mock(ClassType.class);
    ModelIndex modelIndex = Mockito.mock(ModelIndex.class);
    AssociationEnd lhs = Mockito.mock(AssociationEnd.class);
    AssociationEnd rhs = Mockito.mock(AssociationEnd.class);
    Multiplicity multiplicity = Mockito.mock(Multiplicity.class);
    TagDefinition tagDefinition = Mockito.mock(TagDefinition.class);
    Range range = Mockito.mock(Range.class);
    List<AssociationEnd> ends = new ArrayList<AssociationEnd>();
    ends.add(lhs);
    ends.add(rhs);
    Mockito.when(modelIndex.getAssociationEnds(Matchers.any(Identifier.class))).thenReturn(ends);
    Mockito.when(modelIndex.getTagDefinition(Matchers.any(Identifier.class))).thenReturn(tagDefinition);
    Mockito.when(lhs.getMultiplicity()).thenReturn(multiplicity);
    Mockito.when(rhs.getMultiplicity()).thenReturn(multiplicity);
    TaggedValue taggedValue = Mockito.mock(TaggedValue.class);
    List<TaggedValue> taggedValueList = new ArrayList<TaggedValue>();
    taggedValueList.add(taggedValue);
    Mockito.when(lhs.getTaggedValues()).thenReturn(taggedValueList);
    Mockito.when(rhs.getTaggedValues()).thenReturn(taggedValueList);
    Mockito.when(multiplicity.getRange()).thenReturn(range);
    Mockito.when(range.getLower()).thenReturn(Occurs.ONE);
    Mockito.when(range.getUpper()).thenReturn(Occurs.ONE);
    Mockito.when(tagDefinition.getName()).thenReturn(SliUmlConstants.TAGDEF_NATURAL_KEY);
    Mockito.when(taggedValue.getValue()).thenReturn("true");

    Mockito.when(lhs.getName()).thenReturn("lhsTest");
    Mockito.when(rhs.getName()).thenReturn("rhsTest");
    Mockito.when(lhs.getType()).thenReturn(Identifier.random());
    Mockito.when(rhs.getType()).thenReturn(Identifier.random());
    Mockito.when(lhs.getAssociatedAttributeName()).thenReturn("attribute");
    Mockito.when(rhs.getAssociatedAttributeName()).thenReturn("attribute");
    Mockito.when(classType.getName()).thenReturn("Association");
    Mockito.when(classType.getId()).thenReturn(Identifier.random());

    method.invoke(visitor, classType, modelIndex);

}