JAVA反射机制定义
:
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
显示toast:
隐藏toast:
Java反射机制主要提供了以下功能: 在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理。
- 获取相应的类对象名称
Class <?> classType = Class.forName( " com.terry.operationClass " );
Class <?> classType = operationClass. class ; - 返回本类对象
Object invokeOperation = classType.newInstance(); - 根据类对象名称去查找对应的方法
Method addMethod = classType.getMethod( " add " , new Class[] {
int . class , int . class }); - 调用查找 到的方法执行此方法的处理
Object result = addMethod.invoke(invokeOperation, new Object[] {
new Integer(first), new Integer(second) });
用途
1.通过反射技术可以访问到其他包名下数据方法等,这些为一些APK换皮肤提供了方便
2. 访问android 隐藏的API
Toast信息框的关闭是由系统管理的,因为hide方法是隐藏的开发者没有办法直接调用,这种情况下可以用发射机制获取这个方法,创建一个显示和隐藏都由开发者控制的Toast信息框。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
package
com.example.reflection;
import
java.lang.reflect.Field;
import
java.lang.reflect.Method;
import
android.content.Context;
import
android.util.Log;
import
android.view.LayoutInflater;
import
android.view.View;
import
android.widget.TextView;
import
android.widget.Toast;
public
class
MyToast
{
Context context=
null
;
Object obj =
null
;
public
MyToast(Context context,String text)
{
this
.context =context;
Toast toast =Toast.makeText(context, text,
1
);
try
{
Field field = toast.getClass().getDeclaredField(
"mTN"
);
field.setAccessible(
true
);
obj =field.get(toast);
}
catch
(Exception e) {
// TODO: handle exception
Log.d(
"AAA"
,
"MyToast Exception--->"
+e.toString());
}
}
public
void
show()
{
try
{
//android4.0以上就要以下处理
// Field mNextViewField = obj.getClass().getDeclaredField("mNextView");
// mNextViewField.setAccessible(true);
// LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View v = inflate.inflate(R.layout.ui_toast, null);
// mNextViewField.set(obj, v);
Method method =obj.getClass().getDeclaredMethod(
"show"
,
null
);
method.invoke(obj,
null
);
}
catch
(Exception e) {
// TODO Auto-generated catch block
Log.d(
"AAA"
,
"show Exception--->"
+e.toString());
e.printStackTrace();
}
}
public
void
hide()
{
try
{
Method method =obj.getClass().getDeclaredMethod(
"hide"
,
null
);
method.invoke(obj,
null
);
}
catch
(Exception e) {
// TODO Auto-generated catch block
Log.d(
"AAA"
,
"hide Exception--->"
+e.toString());
e.printStackTrace();
}
}
}
|
显示toast:
1
2
|
MyToast toast =
new
MyToast(
this
,
"反射机制!"
);
toast.show();
|
toast.hide();
注意在4.0以上的版本中,还需要对Toast 中的View进行处理,如代码中所示
3. 修改某些“不可改” 的系统资源
ListView组件没有提供修改快速滑块图像的API,因此不能直接修改,但可通过反射实现