Example usage for java.lang.reflect Modifier FINAL

List of usage examples for java.lang.reflect Modifier FINAL

Introduction

In this page you can find the example usage for java.lang.reflect Modifier FINAL.

Prototype

int FINAL

To view the source code for java.lang.reflect Modifier FINAL.

Click Source Link

Document

The int value representing the final modifier.

Usage

From source file:com.google.dexmaker.ProxyBuilder.java

private void getMethodsToProxy(Set<MethodSetEntry> sink, Set<MethodSetEntry> seenFinalMethods, Class<?> c) {
    for (Method method : c.getDeclaredMethods()) {
        for (Class<? extends Annotation> annotation : Constants.annotation) {
            if (method.getAnnotation(annotation) != null) {
                MethodSetEntry entry = new MethodSetEntry(method);
                if (seenFinalMethods.contains(entry)) {
                    continue;
                }/*from www  .  j a va  2  s .c o m*/
                if (sink.add(entry)) {
                    MethodEntity entity = new MethodEntity();
                    entity.clazz = c;
                    entity.name = method.getName();
                    entity.params = method.getParameterTypes();
                    entity.method = method;
                    methods.add(entity);
                }
            }
        }

        if (!Constants.method.contains(method.getName())) {
            // ??
            continue;
        }
        if ((method.getModifiers() & Modifier.FINAL) != 0) {
            // Skip final methods, we can't override them. We
            // also need to remember them, in case the same
            // method exists in a parent class.
            seenFinalMethods.add(new MethodSetEntry(method));
            continue;
        }

        if ((method.getModifiers() & STATIC) != 0) {
            // Skip static methods, overriding them has no effect.
            continue;
        }
        if ((method.getModifiers() & PRIVATE) != 0) {
            // Skip static methods, overriding them has no effect.
            continue;
        }
        //         if ((method.getModifiers() & Modifier.PROTECTED) != 0) {
        //            // Skip static methods, overriding them has no effect.
        //            continue;
        //         }
        if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) {
            // Skip finalize method, it's likely important that it execute as normal.
            continue;
        }
        MethodSetEntry entry = new MethodSetEntry(method);
        if (seenFinalMethods.contains(entry)) {
            // This method is final in a child class.
            // We can't override it.
            continue;
        }
        if (sink.add(entry)) {
            MethodEntity entity = new MethodEntity();
            entity.clazz = c;
            entity.name = method.getName();
            entity.params = method.getParameterTypes();
            entity.method = method;
            methods.add(entity);
        }
    }

    for (Class<?> i : c.getInterfaces()) {
        getMethodsToProxy(sink, seenFinalMethods, i);
    }
}

From source file:org.wso2.carbon.identity.openidconnect.DefaultOIDCClaimsCallbackHandlerTest.java

private void setStaticField(Class classname, String fieldName, Object value)
        throws NoSuchFieldException, IllegalAccessException {

    Field declaredField = classname.getDeclaredField(fieldName);
    declaredField.setAccessible(true);//from w  w w  .jav a 2 s. co m

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(declaredField, declaredField.getModifiers() & ~Modifier.FINAL);

    declaredField.set(null, value);
}

From source file:org.apache.hadoop.hbase.client.TestHCM.java

private int setNumTries(HConnectionImplementation hci, int newVal) throws Exception {
    Field numTries = hci.getClass().getDeclaredField("numTries");
    numTries.setAccessible(true);/*from   w ww.  j a v a  2 s. c  om*/
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(numTries, numTries.getModifiers() & ~Modifier.FINAL);
    final int prevNumRetriesVal = (Integer) numTries.get(hci);
    numTries.set(hci, newVal);

    return prevNumRetriesVal;
}

From source file:org.jgentleframework.utils.ReflectUtils.java

/**
 * Sets new value to static final field.
 * <p>//from  w w w.  j a v  a2 s. co m
 * <b>Note</b>: this method only run on Sun JDK
 * 
 * @param field
 *            the field
 * @param value
 *            the new value
 * @throws NoSuchFieldException
 *             the no such field exception
 * @throws IllegalAccessException
 *             the illegal access exception
 */
public static void setStaticFinalField(Field field, Object value)
        throws NoSuchFieldException, IllegalAccessException {

    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField(MODIFIERS_FIELD);
    modifiersField.setAccessible(true);
    int modifiers = modifiersField.getInt(field);
    modifiers &= ~Modifier.FINAL;
    modifiersField.setInt(field, modifiers);
    FieldAccessor fa = reflection.newFieldAccessor(field, false);
    fa.set(null, value);
}

From source file:org.apache.hive.jdbc.TestJdbcWithMiniHS2.java

private void setReflectionUtilCache() {
    Field constructorCacheField;//from   ww  w  . ja v a  2  s.  c o m
    Cache<Class<?>, Constructor<?>> tmp;
    try {
        constructorCacheField = ReflectionUtil.class.getDeclaredField("CONSTRUCTOR_CACHE");
        if (constructorCacheField != null) {
            constructorCacheField.setAccessible(true);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(constructorCacheField,
                    constructorCacheField.getModifiers() & ~Modifier.FINAL);
            tmp = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.SECONDS).concurrencyLevel(64)
                    .weakKeys().weakValues().build();
            constructorCacheField.set(tmp.getClass(), tmp);
        }
    } catch (Exception e) {
        System.out.println("Error when setting the CONSTRUCTOR_CACHE to expire: " + e);
    }
}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java

@Test(dataProvider = "providePathExistsData")
public void testGetFormPostRedirectPage(String carbonHome, boolean fileExists) throws Exception {
    spy(CarbonUtils.class);
    doReturn(carbonHome).when(CarbonUtils.class, "getCarbonHome");

    Method getFormPostRedirectPage = authzEndpointObject.getClass()
            .getDeclaredMethod("getFormPostRedirectPage");
    getFormPostRedirectPage.setAccessible(true);
    String value = (String) getFormPostRedirectPage.invoke(authzEndpointObject);
    assertEquals((value != null), fileExists, "FormPostRedirectPage value is incorrect");

    Field formPostRedirectPage = authzEndpointObject.getClass().getDeclaredField("formPostRedirectPage");

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);/*from   w  ww.j av  a 2 s .c  o m*/
    modifiersField.setInt(formPostRedirectPage, formPostRedirectPage.getModifiers() & ~Modifier.FINAL);
    formPostRedirectPage.setAccessible(true);
    formPostRedirectPage.set(authzEndpointObject, value);

    Method createFormPage = authzEndpointObject.getClass().getDeclaredMethod("createFormPage", String.class,
            String.class, String.class, String.class);
    createFormPage.setAccessible(true);
    value = (String) createFormPage.invoke(authzEndpointObject, APP_REDIRECT_URL_JSON, APP_REDIRECT_URL,
            StringUtils.EMPTY, "sessionDataValue");
    assertNotNull(value, "Form post page is null");
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerTest.java

@Test
public void testBacklogCursor() throws Exception {
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("cache_backlog_ledger");

    final long maxMessageCacheRetentionTimeMillis = 100;
    Field field = ManagedLedgerImpl.class.getDeclaredField("maxMessageCacheRetentionTimeMillis");
    field.setAccessible(true);/*from w  w  w.  j  av a 2s .c  om*/
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(ledger, maxMessageCacheRetentionTimeMillis);
    Field backlogThresholdField = ManagedLedgerImpl.class.getDeclaredField("maxActiveCursorBacklogEntries");
    backlogThresholdField.setAccessible(true);
    final long maxActiveCursorBacklogEntries = (long) backlogThresholdField.get(ledger);

    // Open Cursor also adds cursor into activeCursor-container
    ManagedCursor cursor1 = ledger.openCursor("c1");
    ManagedCursor cursor2 = ledger.openCursor("c2");

    final int totalBacklogSizeEntries = (int) maxActiveCursorBacklogEntries;
    CountDownLatch latch = new CountDownLatch(totalBacklogSizeEntries);
    for (int i = 0; i < totalBacklogSizeEntries + 1; i++) {
        String content = "entry"; // 5 bytes
        ByteBuf entry = getMessageWithMetadata(content.getBytes());
        ledger.asyncAddEntry(entry, new AddEntryCallback() {
            @Override
            public void addComplete(Position position, Object ctx) {
                latch.countDown();
                entry.release();
            }

            @Override
            public void addFailed(ManagedLedgerException exception, Object ctx) {
                latch.countDown();
                entry.release();
            }

        }, null);
    }
    latch.await();

    // Verify: cursors are active as :haven't started deactivateBacklogCursor scan
    assertTrue(cursor1.isActive());
    assertTrue(cursor2.isActive());

    // it allows message to be older enough to be considered in backlog
    Thread.sleep(maxMessageCacheRetentionTimeMillis * 2);

    // deactivate backlog cursors
    ledger.checkBackloggedCursors();
    Thread.sleep(100);

    // both cursors have to be inactive
    assertFalse(cursor1.isActive());
    assertFalse(cursor2.isActive());

    // read entries so, cursor1 reaches maxBacklog threshold again to be active again
    List<Entry> entries1 = cursor1.readEntries(50);
    for (Entry entry : entries1) {
        log.info("Read entry. Position={} Content='{}'", entry.getPosition(), new String(entry.getData()));
        entry.release();
    }

    // activate cursors which caught up maxbacklog threshold
    ledger.checkBackloggedCursors();

    // verify: cursor1 has consumed messages so, under maxBacklog threshold => active
    assertTrue(cursor1.isActive());

    // verify: cursor2 has not consumed messages so, above maxBacklog threshold => inactive
    assertFalse(cursor2.isActive());

    ledger.close();
}

From source file:org.apache.hadoop.hbase.HBaseTestingUtility.java

/**
 * Tasktracker has a bug where changing the hadoop.log.dir system property
 * will not change its internal static LOG_DIR variable.
 *//* w w w .java2  s.c  om*/
private void forceChangeTaskLogDir() {
    Field logDirField;
    try {
        logDirField = TaskLog.class.getDeclaredField("LOG_DIR");
        logDirField.setAccessible(true);

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(logDirField, logDirField.getModifiers() & ~Modifier.FINAL);

        logDirField.set(null, new File(hadoopLogDir, "userlogs"));
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.carbon.apimgt.impl.AbstractAPIManagerTestCase.java

private static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);//w  w  w.  j  a  v a2 s. c  o  m
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, newValue);
}

From source file:com.codename1.impl.android.AndroidImplementation.java

private static void allowPatch(HttpURLConnection connection) {
    if (enabledPatch) {
        return;/*from  w  ww .  j  a v a 2s .c  o m*/
    }
    if (patchFailed) {
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
        return;
    }
    try {
        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

        methodsField.setAccessible(true);

        String[] oldMethods = (String[]) methodsField.get(null);
        Set<String> methodsSet = new LinkedHashSet<String>(Arrays.asList(oldMethods));
        methodsSet.addAll(Arrays.asList("PATCH"));
        String[] newMethods = methodsSet.toArray(new String[0]);

        methodsField.set(null/*static field*/, newMethods);
        enabledPatch = true;
    } catch (NoSuchFieldException e) {
        patchFailed = true;
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
    } catch (IllegalAccessException ee) {
        patchFailed = true;
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
    }
}