下面列出了java.lang.reflect.Field#getInt ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Get system file descriptor from FileDescriptor object.
* @param descriptor - FileDescriptor objec to get fd from
* @return file descriptor, -1 or error
*/
public static int getfd(FileDescriptor descriptor)
{
Field field = FBUtilities.getProtectedField(descriptor.getClass(), "fd");
if (field == null)
return -1;
try
{
return field.getInt(descriptor);
}
catch (Exception e)
{
JVMStabilityInspector.inspectThrowable(e);
logger.warn("unable to read fd field from FileDescriptor");
}
return -1;
}
private void setCursorColor(EditText view, @ColorInt int color) {
try {
// Get the cursor resource id
Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
field.setAccessible(true);
int drawableResId = field.getInt(view);
// Get the editor
field = TextView.class.getDeclaredField("mEditor");
field.setAccessible(true);
Object editor = field.get(view);
// Get the drawable and set a color filter
Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId);
if (drawable != null) {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
Drawable[] drawables = {drawable, drawable};
// Set the drawables
field = editor.getClass().getDeclaredField("mCursorDrawable");
field.setAccessible(true);
field.set(editor, drawables);
} catch (Exception ignored) {
}
}
private static Map<Integer, String> buildJdbcTypeMap() {
HashMap<Integer, String> map = new HashMap<Integer, String>();
Field[] fields = java.sql.Types.class.getFields();
if ( fields == null ) {
throw new HibernateException( "Unexpected problem extracting JDBC type mapping codes from java.sql.Types" );
}
for ( Field field : fields ) {
try {
final int code = field.getInt( null );
String old = map.put( code, field.getName() );
if ( old != null ) {
LOG.JavaSqlTypesMappedSameCodeMultipleTimes( code, old, field.getName() );
}
}
catch ( IllegalAccessException e ) {
throw new HibernateException( "Unable to access JDBC type mapping [" + field.getName() + "]", e );
}
}
return Collections.unmodifiableMap( map );
}
/**
* 检查当前Activity是否是使用appcompat-v7主题,
* 判断方式参考appcompat-v7 25.3.1版本,其他版本判断方式可能不同
*
* @return true使用appcompat-v7主题,false其他主题
*/
@SuppressFBWarnings("REC_CATCH_EXCEPTION")
private boolean useAppCompatTheme() {
try {
Class styleCls = mContentProxy.getClassLoader().findClassFast("android.support.v7.appcompat.R$styleable");
Field themeField = styleCls.getDeclaredField("AppCompatTheme");
themeField.setAccessible(true);
int[] compatTheme = (int[]) themeField.get(null);
Field actionBarField = styleCls.getDeclaredField("AppCompatTheme_windowActionBar");
actionBarField.setAccessible(true);
int compatActionBar = actionBarField.getInt(null);
TypedArray a = obtainStyledAttributes(compatTheme);
boolean res = a.hasValue(compatActionBar);
a.recycle();
return res;
} catch (Exception e) {
// 当插件中没有使用 appcompat 主题时,会进入到该异常分支。属于正常情况,不需要输出日志
return false;
}
}
private static int getVKMnemonic(String key) {
String s = String.valueOf(getMnemonic(key));
if ( s == null || s.length() != 1) {
return 0;
}
String vkString = "VK_" + s.toUpperCase();
try {
if (_keyEventClazz == null) {
_keyEventClazz= Class.forName("java.awt.event.KeyEvent",
true, (ServiceDialog.class).getClassLoader());
}
Field field = _keyEventClazz.getDeclaredField(vkString);
int value = field.getInt(null);
return value;
} catch (Exception e) {
}
return 0;
}
/**
* 设置状态栏字体图标为深色,需要 MIUIV6 以上
*
* @param window 需要设置的窗口
* @param light 是否把状态栏字体及图标颜色设置为深色
* @return boolean 成功执行返回 true
*/
@SuppressWarnings("unchecked")
public static boolean MIUISetStatusBarLightMode(Window window, boolean light) {
boolean result = false;
if (window != null) {
Class clazz = window.getClass();
try {
int darkModeFlag;
Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
if (light) {
extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
} else {
extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
}
result = true;
} catch (Exception ignored) {
}
}
return result;
}
public static void setFailsafeFieldValue(Field field, Object target, Object value)
throws NoSuchFieldException, IllegalAccessException {
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
try {
FieldAccessor fa = ReflectionFactory.getReflectionFactory().newFieldAccessor(field, false);
fa.set(target, value);
} catch (NoSuchMethodError error) {
field.set(target, value);
}
}
public static boolean miuiSetStatusBarLightMode(Window window, boolean dark) {
boolean result = false;
if (window != null) {
Class<?> clazz = window.getClass();
try {
int darkModeFlag;
@SuppressLint("PrivateApi")
Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
if (dark) {
extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
} else {
extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
}
result = true;
} catch (Exception ignored) {
}
}
return result;
}
private static int getPID(Process process) {
int pid = -1;
try {
if (process instanceof NativeProcess) {
pid = ((NativeProcess) process).getPID();
} else {
String className = process.getClass().getName();
// TODO: windows?...
if ("java.lang.UNIXProcess".equals(className)) { // NOI18N
Field f = process.getClass().getDeclaredField("pid"); // NOI18N
f.setAccessible(true);
pid = f.getInt(process);
}
}
} catch (Throwable e) {
org.netbeans.modules.nativeexecution.support.Logger.getInstance().log(Level.FINE, e.getMessage(), e);
}
return pid;
}
@Override public String toString() {
Field[] fields = getFields(this);
String r="";
for( Field field : fields ){
String name = field.getName();
Class cl = field.getType();
try{
if( cl.isPrimitive() ){
if( cl == Boolean.TYPE ){
boolean curval = field.getBoolean(this);
if( curval ) r += " -"+name;
}
else if( cl == Integer.TYPE ) r+=" -"+name+"="+field.getInt(this);
else if( cl == Float.TYPE ) r+=" -"+name+"="+field.getFloat(this);
else if( cl == Double.TYPE ) r+=" -"+name+"="+field.getDouble(this);
else if( cl == Long.TYPE ) r+=" -"+name+"="+field.getLong(this);
else continue;
} else if( cl == String.class )
if (field.get(this)!=null) r+=" -"+name+"="+field.get(this);
} catch( Exception e ) { Log.err("Argument failed with ",e); }
}
return r;
}
/**
* Returns a map of public static final integer fields in the specified
* classes, to their String representations. An optional filter can be
* specified to only include specific fields. The target map may be null, in
* which case a new map is allocated and returned.
*
* <p>
* This method is useful when debugging to quickly identify values returned
* from an API.</p>
*
* @param filter the filter to use (optional)
* @param target the target map (optional)
* @param tokenClasses the classes to get tokens from
*
* @return the token map
*/
public static Map<Integer, String> apiClassTokens(TokenFilter filter, Map<Integer, String> target, Class<?>... tokenClasses) {
if (target == null) {
target = new HashMap<Integer, String>(64);
}
int TOKEN_MODIFIERS = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL;
for (Class<?> tokenClass : tokenClasses) {
if (tokenClass == null) {
continue;
}
for (Field field : tokenClass.getDeclaredFields()) {
// Get only <public static final int> fields.
if ((field.getModifiers() & TOKEN_MODIFIERS) == TOKEN_MODIFIERS && field.getType() == int.class) {
try {
int value = field.getInt(null);
if (filter != null && !filter.accept(field, value)) {
continue;
}
String name = target.get(value);
target.put(value, name == null ? field.getName() : name + "|" + field.getName());
} catch (IllegalAccessException e) {
// Ignore
}
}
}
}
return target;
}
public static boolean isLolliPopOrLater()
{
int LOLLIPOP = -1;
try {
Field f = Build.VERSION_CODES.class.getField("LOLLIPOP");
if(f != null)
LOLLIPOP =f.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
return LOLLIPOP !=-1 && android.os.Build.VERSION.SDK_INT >= LOLLIPOP;//android.os.Build.VERSION_CODES.LOLLIPOP;
}
/**
* 设置状态栏图标为深色和魅族特定的文字风格
* 可以用来判断是否为 Flyme 用户
*
* @param window 需要设置的窗口
* @param light 是否把状态栏字体及图标颜色设置为深色
* @return boolean 成功执行返回true
*/
public static boolean FlymeSetStatusBarLightMode(Window window, boolean light) {
boolean result = false;
if (window != null) {
Android6SetStatusBarLightMode(window, light);
// flyme 在 6.2.0.0A 支持了 Android 官方的实现方案,旧的方案失效
// 高版本调用这个出现不可预期的 Bug,官方文档也没有给出完整的高低版本兼容方案
if (SkinDeviceUtils.isFlymeLowerThan(7)) {
try {
WindowManager.LayoutParams lp = window.getAttributes();
Field darkFlag = WindowManager.LayoutParams.class
.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
Field meizuFlags = WindowManager.LayoutParams.class
.getDeclaredField("meizuFlags");
darkFlag.setAccessible(true);
meizuFlags.setAccessible(true);
int bit = darkFlag.getInt(null);
int value = meizuFlags.getInt(lp);
if (light) {
value |= bit;
} else {
value &= ~bit;
}
meizuFlags.setInt(lp, value);
window.setAttributes(lp);
result = true;
} catch (Exception ignored) {
}
} else if (SkinDeviceUtils.isFlyme()) {
result = true;
}
}
return result;
}
private static int detectVersion() {
int apiVersion = Opcodes.ASM4;
for (Field field : Opcodes.class.getDeclaredFields()) {
if (field.getType() != Integer.TYPE || !field.getName().startsWith("ASM")) {
continue;
}
try {
int version = field.getInt(null);
// int patch = version & 0xFF;
int minor = (version >> 8) & 0xFF;
int major = (version >> 16) & 0xFF;
boolean experimental = ((version >> 24) & 0xFF) != 0;
if (major >= ASM.majorVersion) {
ASM.maxVersion = field.getName();
if (!experimental) {
apiVersion = version;
ASM.majorVersion = major;
ASM.minorVersion = minor;
}
}
} catch (ReflectiveOperationException ex) {
throw new Error(ex);
}
}
return apiVersion;
}
/**
* 获取进程id
*
* @param process
* @return
*/
public static int getPid(Process process) {
if (process.getClass().getName().equals("java.lang.UNIXProcess")) {
try {
Field f = process.getClass().getDeclaredField("pid");
f.setAccessible(true);
return f.getInt(process);
} catch (Throwable e) {
throw new RuntimeException("something goew wrong when get pid", e);
}
} else {
// 其它系统暂不支持
throw new RuntimeException("unsupported operation system,can't get the pid");
}
}
public boolean hasEarpiece() {
if(USE_CONNECTION_SERVICE){
if(systemCallConnection!=null && systemCallConnection.getCallAudioState()!=null){
int routeMask=systemCallConnection.getCallAudioState().getSupportedRouteMask();
return (routeMask & (CallAudioState.ROUTE_EARPIECE | CallAudioState.ROUTE_WIRED_HEADSET))!=0;
}
}
if(((TelephonyManager)getSystemService(TELEPHONY_SERVICE)).getPhoneType()!=TelephonyManager.PHONE_TYPE_NONE)
return true;
if (mHasEarpiece != null) {
return mHasEarpiece;
}
// not calculated yet, do it now
try {
AudioManager am=(AudioManager)getSystemService(AUDIO_SERVICE);
Method method = AudioManager.class.getMethod("getDevicesForStream", Integer.TYPE);
Field field = AudioManager.class.getField("DEVICE_OUT_EARPIECE");
int earpieceFlag = field.getInt(null);
int bitmaskResult = (int) method.invoke(am, AudioManager.STREAM_VOICE_CALL);
// check if masked by the earpiece flag
if ((bitmaskResult & earpieceFlag) == earpieceFlag) {
mHasEarpiece = Boolean.TRUE;
} else {
mHasEarpiece = Boolean.FALSE;
}
} catch (Throwable error) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("Error while checking earpiece! ", error);
}
mHasEarpiece = Boolean.TRUE;
}
return mHasEarpiece;
}
public static int getIntFieldIfExists(Class<?> klass, String fieldName,
Class<?> obj, int defaultVal) {
try {
Field f = klass.getDeclaredField(fieldName);
return f.getInt(obj);
} catch (Exception e) {
return defaultVal;
}
}
int getDepth(Throwable t) throws Exception {
Field f = Throwable.class.getDeclaredField("depth");
f.setAccessible(true); // it's private
return f.getInt(t);
}
public ServiceContextData( Class cls )
{
if (ORB.ORBInitDebug)
dprint( "ServiceContextData constructor called for class " + cls ) ;
scClass = cls ;
try {
if (ORB.ORBInitDebug)
dprint( "Finding constructor for " + cls ) ;
// Find the appropriate constructor in cls
Class[] args = new Class[2] ;
args[0] = InputStream.class ;
args[1] = GIOPVersion.class;
try {
scConstructor = cls.getConstructor( args ) ;
} catch (NoSuchMethodException nsme) {
throwBadParam( "Class does not have an InputStream constructor", nsme ) ;
}
if (ORB.ORBInitDebug)
dprint( "Finding SERVICE_CONTEXT_ID field in " + cls ) ;
// get the ID from the public static final int SERVICE_CONTEXT_ID
Field fld = null ;
try {
fld = cls.getField( "SERVICE_CONTEXT_ID" ) ;
} catch (NoSuchFieldException nsfe) {
throwBadParam( "Class does not have a SERVICE_CONTEXT_ID member", nsfe ) ;
} catch (SecurityException se) {
throwBadParam( "Could not access SERVICE_CONTEXT_ID member", se ) ;
}
if (ORB.ORBInitDebug)
dprint( "Checking modifiers of SERVICE_CONTEXT_ID field in " + cls ) ;
int mod = fld.getModifiers() ;
if (!Modifier.isPublic(mod) || !Modifier.isStatic(mod) ||
!Modifier.isFinal(mod) )
throwBadParam( "SERVICE_CONTEXT_ID field is not public static final", null ) ;
if (ORB.ORBInitDebug)
dprint( "Getting value of SERVICE_CONTEXT_ID in " + cls ) ;
try {
scId = fld.getInt( null ) ;
} catch (IllegalArgumentException iae) {
throwBadParam( "SERVICE_CONTEXT_ID not convertible to int", iae ) ;
} catch (IllegalAccessException iae2) {
throwBadParam( "Could not access value of SERVICE_CONTEXT_ID", iae2 ) ;
}
} catch (BAD_PARAM nssc) {
if (ORB.ORBInitDebug)
dprint( "Exception in ServiceContextData constructor: " + nssc ) ;
throw nssc ;
} catch (Throwable thr) {
if (ORB.ORBInitDebug)
dprint( "Unexpected Exception in ServiceContextData constructor: " +
thr ) ;
}
if (ORB.ORBInitDebug)
dprint( "ServiceContextData constructor completed" ) ;
}
public void testInitOrder () throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
final Field f = new GroovyClassLoader().loadClass("org.codehaus.groovy.runtime.XforStaticInitTest", false, false, false).getField("field");
assertTrue(!failed);
f.getInt(null);
assertTrue(failed);
}