Transferred from: http://blog.csdn.net/yaerfeng/article/details/7103397
Today the project encountered a problem, to invoke a class, and get the properties of the class to be assigned and then pass the class to the method as a parameter.
The actual operation only found that the field properties in this class are private and cannot be assigned! There are no public methods available. And this class is packaged as a jar for me, and I can't change its code so that it's a problem to write a set method manually. Later thought with reflection can solve this problem, so tried, sure enough!
Reflection does not seem to differentiate whether it is private, it is possible to call its own private method, but it is not possible to invoke the private method of the parent class, which is probably because the Getdeclaredmethod method and the GetMethod method do not find the private method of the parent class. It can be solved by writing your own recursion, but the performance will not be too good using reflection.
Let's look at the code below.
[Java]View Plaincopyprint?
- field[] fields = Obj.getdeclaredfields ();
- For (int i = 0; i < fields.length; i++) {
- Fields[i].setaccessible (true);
- For (int j = 0; j < Args.length; J + +) {
- String str = args[j];
- String strs[] = Str.split (",");
- if (strs[0].equals (Fields[i].getname ())) {
- Fields[i].set (Object, strs[1]);
- Break ;
- }
- }
- }
[Java]View Plaincopyprint?
- Fields[i].setaccessible (true);
This sentence is the key. Look at the surface of it the English meaning is set to accessible as: true. Programming meaning everyone should know.
By looking at the source code of the JDK:
[Java]View Plaincopyprint?
- Public void Setaccessible (boolean flag) throws SecurityException {
- SecurityManager sm = System.getsecuritymanager ();
- if (sm! = null) sm.checkpermission (access_permission);
- SETACCESSIBLE0 (this, flag);
- }
We can see that it manages permissions through SecurityManager, and we can enable Java.security.manager to determine whether the program has permission to invoke Setaccessible (). By default, the kernel API and code for the extended directory have this permission, and the classpath or applications loaded through URLClassLoader do not have this permission. For example, an exception will be thrown when we execute the above program in this way
[Java]View Plaincopyprint?
- Java.security.AccessControlException:access denied
In general, we do not operate on private fields of classes, but sometimes we have to be able to handle these fields, and we need to invoke the Setaccessible () method on AccessibleObject to allow such access, Because Field,method and constructor in reflection classes inherit from AccessibleObject, we can implement operations on these fields by invoking the Setaccessible () method on those classes.
Let's take a look at how this access_permission is handled:
[Java]View Plaincopyprint?
- Static final private java.security.Permission access_permission =
- New Reflectpermission ("suppressaccesschecks");
Find the JDK Help documentation to see a detailed explanation:
Public final class Reflectpermissionextends basicpermission
The Permission class for the reflection operation. Reflectpermission is aSpecify Permissions, no action. The unique name of the current definition isSuppressaccesschecks, which allows the cancellation of standard Java language access checks performed by reflection objects on their point of use-for public, default (package) access, protected, private members. The following table provides a brief description of the permissions allowed and discusses the risks of granting permissions to the code.
| Permission Target Name |
content allowed by permissions |
risk of allowing this permission |
| Suppressaccesschecks |
Ability to access fields and invoke methods in a class. Note that this includes not only public, but also protected and private fields and methods. |
The risk is that information that is normally unavailable (perhaps classified information) and methods may be subject to malicious code access. |
It's a little clear here. Fields.setaccessible (True), the actual function is to enable access to the Public,protected,private field!
Isn't that cool? Of course, this method destroys the original permission system of Java. So it is not a last resort, or less, the efficiency of reflection is not so high after all.
Okay, we got this. We'll write a universal universal method, just pass the corresponding class, field name and value, we reflect it inside the method and instantiate it. The corresponding field is then assigned the value. Because I only used the field. You can add the other stuff. Well. This is fun.
[Java]View Plaincopyprint?
- Package unit.sms;
- Public class Smss {
- private String DestID;
- private String content;
- Private String Mobile;
- Public String Getdestid () {
- return DestID;
- }
- Public String getcontent () {
- return content;
- }
- Public String Getmobile () {
- return mobile;
- }
- }
[Java]View Plaincopyprint?
- Package com.sinoglobal.utils;
- Import Java.lang.reflect.Field;
- Import Com.jasson.mas.api.smsapi.Sms;
- /**
- * Common tool class for reflection
- *
- * @author LZ
- *
- */
- Public class Reflectionutils {
- /**
- * Used to assign values to fields of a class, ignoring the Private,project modifier, ignoring the Set/get method
- * @param c class to reflect
- * @param the field name and value of the args class each field name and value is separated by commas
- * @return
- */
- @SuppressWarnings ("unchecked")
- public static Object getinstance (Class C, String ... args) {
- try {
- Object object = Class.forName (C.getname ()). Newinstance ();
- class<?> obj = Object.getclass ();
- field[] fields = Obj.getdeclaredfields ();
- For (int i = 0; i < fields.length; i++) {
- Fields[i].setaccessible (true);
- For (int j = 0; j < Args.length; J + +) {
- String str = args[j];
- String strs[] = Str.split (",");
- if (strs[0].equals (Fields[i].getname ())) {
- Fields[i].set (Object, strs[1]);
- Break ;
- }
- }
- }
- return object;
- } catch (Illegalaccessexception e) {
- E.printstacktrace ();
- } catch (ClassNotFoundException e) {
- E.printstacktrace ();
- } catch (Instantiationexception e) {
- E.printstacktrace ();
- }
- return null;
- }
- public static void Main (string[] args) {
- Object object = getinstance (Smss.class, "destid,01201101", "mobile,15810022404", "content," test data. ");
- Smss SMS = (SMSS) object;
- SYSTEM.OUT.PRINTLN ("SMS content:" + sms.getcontent ());
- System.out.println ("mobile phone Number:" + sms.getmobile ());
- System.out.println ("tail Number:" + sms.getdestid ());
- }
- }
Console output:
Message content: Test data.
Phone Number: 15810022404
Tail Number: 01201101
Fields.setaccessible (TRUE); The use of May everyone, but we have to do is, know it, know why.
Looking at the source code of JDK is undoubtedly the best way to learn and solve this method.
over~~~
Java advanced Programming-forcing the private field to be assigned using reflection