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

The following are Jave code examples for showing how to use setAccessible() of the java.lang.reflect.Field 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: KevsPermissions   File: KevsPermissions.java   View Source Code Vote up 6 votes
static void injectToPlayer(Player p, PermissionsPlayer pp) {
	try {
		Method getHandle = p.getClass().getMethod("getHandle");
		Object human = getHandle.invoke(p);
		String pck = new String(human.getClass().getCanonicalName()).split("\\.")[3];
		Field field = Class.forName("org.bukkit.craftbukkit." + pck + ".entity.CraftHumanEntity")
				.getDeclaredField("perm");
		field.setAccessible(true);
		Field modifiersField = field.getClass().getDeclaredField("modifiers");
		modifiersField.setAccessible(true);
		modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
		field.set(p, new KevsPermissible(p));
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 2
Project: incubator-netbeans   File: JavaBinaryIndexerTest.java   View Source Code Vote up 6 votes
private void assertValidIndex(LuceneIndex index) throws ReflectiveOperationException {
    final Field dirCacheFld = LuceneIndex.class.getDeclaredField("dirCache");   //NOI18N
    dirCacheFld.setAccessible(true);
    final Object dirCache = dirCacheFld.get(index);
    assertNotNull(dirCache);
    final Field indexWriterRefFld = dirCache.getClass().getDeclaredField("indexWriterRef"); //NOI18N
    indexWriterRefFld.setAccessible(true);
    final Object indexWriterRef = indexWriterRefFld.get(dirCache);
    final Field modifiedFld = indexWriterRef.getClass().getDeclaredField("modified");   //NOI18N
    modifiedFld.setAccessible(true);
    assertFalse(modifiedFld.getBoolean(indexWriterRef));
    final Field txThreadFld = indexWriterRef.getClass().getDeclaredField("txThread");   //NOI18N
    txThreadFld.setAccessible(true);
    assertNull(txThreadFld.get(indexWriterRef));
    final Field openThreadFld = indexWriterRef.getClass().getDeclaredField("openThread");   //NOI18N
    openThreadFld.setAccessible(true);
    assertNull(openThreadFld.get(indexWriterRef));
}
 
Example 3
Project: GitHub   File: NotExistsTest.java   View Source Code Vote up 5 votes
public void test_0() throws Exception {
        Field field = TypeUtils.class.getDeclaredField("mappings");
        field.setAccessible(true);

        ConcurrentMap<String, Class<?>> mappings = (ConcurrentMap<String, Class<?>>) field.get(null);
        System.out.println(mappings.size());
//         ParserConfig.global.setAutoTypeSupport(true);
        for (int i = 0; i < 10; ++i) {
            long start = System.currentTimeMillis();
            perf();
            long millis = System.currentTimeMillis() - start;
            System.out.println("millis : " + millis);
        }
    }
 
Example 4
Project: SwipeSectorLayout   File: CustomPager.java   View Source Code Vote up 5 votes
private void postInitViewPager() {
    try {
        Field scroller = ViewPager.class.getDeclaredField("mScroller");
        scroller.setAccessible(true);
        Field interpolator = ViewPager.class.getDeclaredField("sInterpolator");
        interpolator.setAccessible(true);
        mScroller = new CustomScroller(getContext(),
                (Interpolator) interpolator.get(null));
        scroller.set(this, mScroller);
    } catch (Exception e) {
    }
}
 
Example 5
Project: stock-api-sdk   File: LicenseHistoryRequestTest.java   View Source Code Vote up 5 votes
@Test(groups = { "Setters" })
void setLicenseHistoryResultColumns_should_set_what_fields_to_be_included_in_Result_and_return_instanceOf_LicenseHistoryRequest()
        throws NoSuchFieldException, IllegalAccessException {
    LicenseHistoryResultColumn[] result = { LicenseHistoryResultColumn.THUMBNAIL_1000_HEIGHT,
            LicenseHistoryResultColumn.THUMBNAIL_1000_URL };
    Assert.assertNotNull(request.setResultColumns(result));
    Field f = request.getClass().getDeclaredField("mResultColumns");
    f.setAccessible(true);
    result = (LicenseHistoryResultColumn[]) f.get(request);
}
 
Example 6
Project: stock-api-sdk   File: StockLicenseHistoryFileTest.java   View Source Code Vote up 5 votes
@Test(groups = { "Getters" })
void getThumbnail110Url_should_return_media_Thumbnail110Url_ofType_String_StockLicenseHistoryFile()
        throws NoSuchFieldException, IllegalAccessException {
    Field f = stocklicensehistoryfile.getClass().getDeclaredField("mThumbnail110Url");
    f.setAccessible(true);
    f.set(stocklicensehistoryfile, "SomeText");
    Assert.assertTrue(stocklicensehistoryfile.getThumbnail110Url().equals("SomeText"));
}
 
Example 7
Project: https-github.com-hyb1996-NoRootScriptDroid   File: Editor920Utils.java   View Source Code Vote up 5 votes
public static Document getDocument(EditorDelegate editorDelegate) {
    try {
        Field field = EditorDelegate.class.getDeclaredField("document");
        field.setAccessible(true);
        return (Document) field.get(editorDelegate);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Project: HCFCore   File: CustomEntityRegistration.java   View Source Code Vote up 5 votes
public static void setFieldPrivateStaticMap(String fieldName, Object key, Object value)
{
    try
    {
        Field field = EntityTypes.class.getDeclaredField(fieldName);
        field.setAccessible(true);
        Map map = (Map)field.get(null);
        map.put(key, value);
        field.set(null, map);
    }
    catch (NoSuchFieldException|SecurityException|IllegalArgumentException|IllegalAccessException ex)
    {
        ex.printStackTrace();
    }
}
 
Example 9
Project: ALTTPMenuPractice   File: MenuPractice.java   View Source Code Vote up 5 votes
private static void addLibraryPath(String pathToAdd) throws Exception {
	Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
	usrPathsField.setAccessible(true);

	String[] paths = (String[]) usrPathsField.get(null);

	for (String path : paths) {
		if (path.equals(pathToAdd)) { return; }
	}

	String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
	newPaths[newPaths.length - 1] = pathToAdd;
	usrPathsField.set(null, newPaths);
}
 
Example 10
Project: litiengine   File: ConfigurationGroup.java   View Source Code Vote up 5 votes
/**
 * Store properties. By default, it is supported to store the following types:
 * boolean, int, double, float, String and enum values. If you need to store
 * any other object, you should overwrite this method as well as the
 * initializeProperty method and implement a custom approach.
 *
 *
 * @param properties
 *          the properties
 */
protected void storeProperties(final Properties properties) {
  try {
    for (final Field field : this.getClass().getDeclaredFields()) {
      if (!field.isAccessible()) {
        field.setAccessible(true);
      }

      if (field.getType().equals(boolean.class)) {
        properties.setProperty(this.getPrefix() + field.getName(), Boolean.toString(field.getBoolean(this)));
      } else if (field.getType().equals(int.class)) {
        properties.setProperty(this.getPrefix() + field.getName(), Integer.toString(field.getInt(this)));
      } else if (field.getType().equals(float.class)) {
        properties.setProperty(this.getPrefix() + field.getName(), Float.toString(field.getFloat(this)));
      } else if (field.getType().equals(double.class)) {
        properties.setProperty(this.getPrefix() + field.getName(), Double.toString(field.getDouble(this)));
      } else if (field.getType().equals(byte.class)) {
        properties.setProperty(this.getPrefix() + field.getName(), Byte.toString(field.getByte(this)));
      } else if (field.getType().equals(short.class)) {
        properties.setProperty(this.getPrefix() + field.getName(), Short.toString(field.getShort(this)));
      } else if (field.getType().equals(long.class)) {
        properties.setProperty(this.getPrefix() + field.getName(), Long.toString(field.getLong(this)));
      } else if (field.getType().equals(String.class)) {
        properties.setProperty(this.getPrefix() + field.getName(), field.get(this) != null ? (String) field.get(this) : "");
      } else if (field.getType().equals(String[].class)) {
        properties.setProperty(this.getPrefix() + field.getName(), field.get(this) != null ? String.join(",", (String[]) field.get(this)) : "");
      } else if (field.getType() instanceof Class && field.getType().isEnum()) {
        Object val = field.get(this);
        final String value = val == null && field.getType().getEnumConstants().length > 0 ? field.getType().getEnumConstants()[0].toString() : "";
        properties.setProperty(this.getPrefix() + field.getName(), val != null ? val.toString() : value);
      }
    }
  } catch (final IllegalArgumentException | IllegalAccessException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }
}
 
Example 11
Project: stock-api-sdk   File: SearchParametersTest.java   View Source Code Vote up 5 votes
@Test(groups = { "Setters" })
void setMediaId_should_set_media_Media_id_and_should_return_instanceof_SearchParameters()
        throws IllegalAccessException,
        NoSuchFieldException {
    Assert.assertNotNull(param.setMediaId(127));
    Field f = param.getClass().getDeclaredField("mMediaId");
    f.setAccessible(true);
    Assert.assertTrue((f.get(param)).equals(127));
}
 
Example 12
Project: GitHub   File: StatefulRunnableTest.java   View Source Code Vote up 5 votes
@Before
public void setUp() throws Exception {
  mResult = new Object();
  mException = new ConcurrentModificationException();
  mStatefulRunnable = mock(StatefulRunnable.class, CALLS_REAL_METHODS);

  // setup state - no constructor has been run
  Field mStateField = StatefulRunnable.class.getDeclaredField("mState");
  mStateField.setAccessible(true);
  mStateField.set(mStatefulRunnable, new AtomicInteger(StatefulRunnable.STATE_CREATED));
  mStateField.setAccessible(false);
}
 
Example 13
Project: oscm-app   File: InitializerTest.java   View Source Code Vote up 5 votes
@SuppressWarnings("boxing")
@Test
public void testLoggingWithFileAccessException() throws Exception {
    File log4jFile = createLog4jFile(LOG4J_CONFIG1);
    try {
        // Set path of log4j properties
        log4jFolderPath = log4jFile.getParentFile().getParent();
        setSysSetting(log4jFolderPath);

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

        // Now we exchange the internal stored file with a mockup :)
        File oopsFile = Mockito.mock(File.class);
        Field fileField = testElm.getClass().getDeclaredField("logFile");
        fileField.setAccessible(true);
        fileField.set(testElm, oopsFile);

        // And enable damage!
        Mockito.when(oopsFile.lastModified()).thenThrow(
                new SecurityException());

        // Simulate timer (-> this will now result in a security exception!)
        testElm.handleTimer(null);

        // Simulate timer (-> this will now result in a security exception!)
        testElm.handleTimer(null);

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

}
 
Example 14
Project: android-dev-challenge   File: TestUtilities.java   View Source Code Vote up 5 votes
static Integer getStaticIntegerField(Class clazz, String variableName)
        throws NoSuchFieldException, IllegalAccessException {
    Field intField = clazz.getDeclaredField(variableName);
    intField.setAccessible(true);
    Integer value = (Integer) intField.get(null);
    return value;
}
 
Example 15
Project: silly-android   File: AnnotationParser.java   View Source Code Vote up 5 votes
/**
 * Assigns an integer to the given field.
 *
 * @param instance  A non-{@code null} instance that holds the field
 * @param value     The value being set
 * @param fieldName The name of the field being modified
 * @return {@code True} if the value was successfully assigned, {@code false} otherwise
 */
private static boolean setIntFieldValue(@NonNull final Object instance, final int value, @NonNull final String fieldName) {
    // check the cache first (iterating is much faster than reflection)
    Field fieldReference = null;

    List<Field> classFields = getAllFields(instance.getClass());
    for (final Field iField : classFields) {
        if (iField.getName().equals(fieldName)) {
            // found it!
            fieldReference = iField;
            break;
        }
    }

    // if not found, die.
    if (fieldReference == null) {
        throw new IllegalArgumentException("Class '" + instance.getClass().getName() + "' needs to have a '" + fieldName + "' field");
    }

    // finally, set the value
    try {
        fieldReference.setAccessible(true);
        fieldReference.setInt(instance, value);
        return true;
    } catch (IllegalAccessException e) {
        Log.w(TAG, "Failed to set " + value + " to " + fieldName, e);
    }
    return false;
}
 
Example 16
Project: ZentrelaCore   File: CustomSpider.java   View Source Code Vote up 5 votes
public CustomSpider(World world) {
    super(world);
    try {
        Field gsa = PathfinderGoalSelector.class.getDeclaredField("b");
        gsa.setAccessible(true);
        gsa.set(this.goalSelector, Sets.newLinkedHashSet());
        gsa.set(this.targetSelector, Sets.newLinkedHashSet());
    } catch (Exception e) {
        e.printStackTrace();
    }
    this.goalSelector.a(0, new PathfinderGoalFloat(this));
    //        this.goalSelector.a(5, new PathfinderGoalRandomStroll(this, 1.0D, 40));
    this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F));
    this.goalSelector.a(7, new PathfinderGoalRandomLookaround(this));
}
 
Example 17
Project: stock-api-sdk   File: LicenseCompTest.java   View Source Code Vote up 5 votes
@Test(groups = { "Getters" })
void getUrl_should_return_url_of_Type_String_Licensecomp()
        throws NoSuchFieldException, IllegalAccessException {
    Field f = comp.getClass().getDeclaredField("mUrl");
    f.setAccessible(true);
    f.set(comp, "testUrl");
    Assert.assertTrue(comp.getUrl().equals("testUrl"));
}
 
Example 18
Project: incubator-netbeans   File: IndexingSupportACIDTest.java   View Source Code Vote up 5 votes
@Override
public CustomIndexer createIndexer() {
    return new CustomIndexer() {
        @Override
        protected void index(Iterable<? extends Indexable> files, Context context) {
            try {
                final IndexingSupport is = IndexingSupport.getInstance(context);
                for (Indexable i : files) {
                    final IndexDocument doc = is.createDocument(i);
                    is.addDocument(doc);
                }
            } catch (IOException ioe) {
                Exceptions.printStackTrace(ioe);
            }
            if (cancelScanning) {
                try {
                    final Field gwm = RepositoryUpdater.class.getDeclaredField("worker");  //NOI18N
                    gwm.setAccessible(true);
                    final Object task = gwm.get(RepositoryUpdater.getDefault());
                    final Field wipf = task.getClass().getDeclaredField("workInProgress");  //NOI18N
                    wipf.setAccessible(true);
                    RepositoryUpdater.Work work = (RepositoryUpdater.Work) wipf.get(task);
                    work.setCancelled(true);
                } catch (ReflectiveOperationException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };
}
 
Example 19
Project: openjdk-jdk10   File: RMIConnectorInternalMapTest.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    System.out.println("---RMIConnectorInternalMapTest starting...");

    JMXConnectorServer connectorServer = null;
    JMXConnector connectorClient = null;

    try {
        MBeanServer mserver = ManagementFactory.getPlatformMBeanServer();
        JMXServiceURL serverURL = new JMXServiceURL("rmi", "localhost", 0);
        connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serverURL, null, mserver);
        connectorServer.start();

        JMXServiceURL serverAddr = connectorServer.getAddress();
        connectorClient = JMXConnectorFactory.connect(serverAddr, null);
        connectorClient.connect();

        Field rmbscMapField = RMIConnector.class.getDeclaredField("rmbscMap");
        rmbscMapField.setAccessible(true);
        Map<Subject, WeakReference<MBeanServerConnection>> map =
                (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
        if (map != null && !map.isEmpty()) { // failed
            throw new RuntimeException("RMIConnector's rmbscMap must be empty at the initial time.");
        }

        Subject delegationSubject =
                new Subject(true,
                Collections.singleton(new JMXPrincipal("delegate")),
                Collections.EMPTY_SET,
                Collections.EMPTY_SET);
        MBeanServerConnection mbsc1 =
                connectorClient.getMBeanServerConnection(delegationSubject);
        MBeanServerConnection mbsc2 =
                connectorClient.getMBeanServerConnection(delegationSubject);

        if (mbsc1 == null) {
            throw new RuntimeException("Got null connection.");
        }
        if (mbsc1 != mbsc2) {
            throw new RuntimeException("Not got same connection with a same subject.");
        }

        map = (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
        if (map == null || map.isEmpty()) { // failed
            throw new RuntimeException("RMIConnector's rmbscMap has wrong size "
                    + "after creating a delegated connection.");
        }

        delegationSubject = null;
        mbsc1 = null;
        mbsc2 = null;

        int i = 0;
        while (!map.isEmpty() && i++ < 60) {
            System.gc();
            Thread.sleep(100);
        }
        System.out.println("---GC times: " + i);

        if (!map.isEmpty()) {
            throw new RuntimeException("Failed to clean RMIConnector's rmbscMap");
        } else {
            System.out.println("---RMIConnectorInternalMapTest: PASSED!");
        }
    } finally {
        try {
            connectorClient.close();
            connectorServer.stop();
        } catch (Exception e) {
        }
    }
}
 
Example 20
Project: PetBlocks   File: ParticleEffectData.java   View Source Code Vote up 3 votes
/**
 * Sends a packet to the client player
 *
 * @param player player
 * @param packet packet
 * @throws ClassNotFoundException    exception
 * @throws IllegalAccessException    exception
 * @throws NoSuchMethodException     exception
 * @throws InvocationTargetException exception
 * @throws NoSuchFieldException      exception
 */

private static void sendPacket(Player player, Object packet) throws ClassNotFoundException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
    final Object craftPlayer = findClass("org.bukkit.craftbukkit.VERSION.entity.CraftPlayer").cast(player);
    final Object entityPlayer = invokeMethod(craftPlayer, craftPlayer.getClass(), "getHandle", new Class[]{}, new Object[]{});
    final Field field = findClass("net.minecraft.server.VERSION.EntityPlayer").getDeclaredField("playerConnection");
    field.setAccessible(true);
    final Object connection = field.get(entityPlayer);
    invokeMethod(connection, connection.getClass(), "sendPacket", new Class[]{packet.getClass().getInterfaces()[0]}, new Object[]{packet});
}