當前位置: 首頁>>代碼示例>>Java>>正文


Java Field.setAccessible方法代碼示例

本文整理匯總了Java中java.lang.reflect.Field.setAccessible方法的典型用法代碼示例。如果您正苦於以下問題:Java Field.setAccessible方法的具體用法?Java Field.setAccessible怎麽用?Java Field.setAccessible使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.lang.reflect.Field的用法示例。


在下文中一共展示了Field.setAccessible方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: injectToPlayer

import java.lang.reflect.Field; //導入方法依賴的package包/類
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();
	}
}
 
開發者ID:KevSlashNull,項目名稱:KevsPermissions,代碼行數:17,代碼來源:KevsPermissions.java

示例2: assertValidIndex

import java.lang.reflect.Field; //導入方法依賴的package包/類
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));
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:19,代碼來源:JavaBinaryIndexerTest.java

示例3: test_0

import java.lang.reflect.Field; //導入方法依賴的package包/類
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);
        }
    }
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:15,代碼來源:NotExistsTest.java

示例4: postInitViewPager

import java.lang.reflect.Field; //導入方法依賴的package包/類
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) {
    }
}
 
開發者ID:lycheetw,項目名稱:SwipeSectorLayout,代碼行數:13,代碼來源:CustomPager.java

示例5:

import java.lang.reflect.Field; //導入方法依賴的package包/類
@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);
}
 
開發者ID:adobe,項目名稱:stock-api-sdk,代碼行數:11,代碼來源:LicenseHistoryRequestTest.java

示例6: getThumbnail110Url_should_return_media_Thumbnail110Url_ofType_String_StockLicenseHistoryFile

import java.lang.reflect.Field; //導入方法依賴的package包/類
@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"));
}
 
開發者ID:adobe,項目名稱:stock-api-sdk,代碼行數:9,代碼來源:StockLicenseHistoryFileTest.java

示例7: getDocument

import java.lang.reflect.Field; //導入方法依賴的package包/類
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);
    }
}
 
開發者ID:feifadaima,項目名稱:https-github.com-hyb1996-NoRootScriptDroid,代碼行數:10,代碼來源:Editor920Utils.java

示例8: setFieldPrivateStaticMap

import java.lang.reflect.Field; //導入方法依賴的package包/類
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();
    }
}
 
開發者ID:funkemunky,項目名稱:HCFCore,代碼行數:16,代碼來源:CustomEntityRegistration.java

示例9: addLibraryPath

import java.lang.reflect.Field; //導入方法依賴的package包/類
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);
}
 
開發者ID:fatmanspanda,項目名稱:ALTTPMenuPractice,代碼行數:15,代碼來源:MenuPractice.java

示例10: storeProperties

import java.lang.reflect.Field; //導入方法依賴的package包/類
/**
 * 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);
  }
}
 
開發者ID:gurkenlabs,項目名稱:litiengine,代碼行數:46,代碼來源:ConfigurationGroup.java

示例11: setMediaId_should_set_media_Media_id_and_should_return_instanceof_SearchParameters

import java.lang.reflect.Field; //導入方法依賴的package包/類
@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));
}
 
開發者ID:adobe,項目名稱:stock-api-sdk,代碼行數:10,代碼來源:SearchParametersTest.java

示例12: setUp

import java.lang.reflect.Field; //導入方法依賴的package包/類
@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);
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:13,代碼來源:StatefulRunnableTest.java

示例13: testLoggingWithFileAccessException

import java.lang.reflect.Field; //導入方法依賴的package包/類
@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();
    }

}
 
開發者ID:servicecatalog,項目名稱:oscm-app,代碼行數:38,代碼來源:InitializerTest.java

示例14: getStaticIntegerField

import java.lang.reflect.Field; //導入方法依賴的package包/類
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;
}
 
開發者ID:fjoglar,項目名稱:android-dev-challenge,代碼行數:8,代碼來源:TestUtilities.java

示例15: setIntFieldValue

import java.lang.reflect.Field; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:milosmns,項目名稱:silly-android,代碼行數:37,代碼來源:AnnotationParser.java


注:本文中的java.lang.reflect.Field.setAccessible方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。