Today, a problem occurs in the project. You need to call a class, obtain the attributes of the class, assign values, and pass the class to the method as a parameter.
During actual operations, we found that the field attributes in this class are private and cannot be assigned a value! No public method is provided. This class is packaged into jar for me, and I cannot change its code, so it is a problem to manually write a set method for it. Later, I thought that reflection could solve this problem. So I tried it!
Reflection does not seem to distinguish whether it is private. It is possible to call its own private method, but it is not possible to call the private method of the parent class, the possible reason is that the getdeclaredmethod and getmethod methods do not find the private method of the parent class. You can solve this problem by writing recursion on your own. However, if reflection is used, the performance will not be very good.
Let's take a look at the following code.
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;}}}
fields[i].setAccessible(true);
This sentence is the key. It indicates that the value of "true" can be accessed. Programming means everyone should know.
View the JDK source code:
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. We can enable Java. Security. Manager to determine whether the program has the permission to call setaccessible. By default, the kernel API and extended directory Code have this permission, but the class path or the application loaded through urlclassloader does not. For example, when we execute the above program in this way, an exception will be thrown.
java.security.AccessControlException: access denied
Generally, we cannot operate private fields of the class, but sometimes we must be able to process these fields. At this time, we need to call setaccessible () on the accessibleobject () method to allow this access. Because the field, method, and constructor in the reflection class inherit from accessibleobject, you can call the setaccessible () method on these classes, we can perform operations on these fields.
Let's take a look at how this access_permission is handled:
static final private java.security.Permission ACCESS_PERMISSION =new ReflectPermission("suppressAccessChecks");
Find the JDK help document and see the detailed explanation:
-
public final class ReflectPermission
-
Extends basicpermission
The permission class of the reflection operation. Reflectpermission is
Specify Permissions, No action. The unique name of the current definition is SuppressaccesschecksIt allows you to cancel the standard Java language access check executed by the reflection object on its usage point-for public, default (Package) Access, protected, and private members.
The following table provides a brief description of permitted permissions and discusses the risks of granting code permissions.
| Permission target name |
Permitted content |
Risk of allowing this permission |
| Suppressaccesschecks |
It can be used to call fields and methods in the callback class. Note that this includes not only public, but also protected and private fields and methods. |
The risk is that the commonly unavailable information (maybe confidential information) and methods may be accessed by malicious code. |
Here is a bit of attention. Fields. setaccessible (true); the actual function is to allow access to public, protected, and private fields!
Is it nice. Of course, this method damages the original Java permission system. Therefore, the reflection efficiency is not that high.
Now that we know this, let's write a universal method, just pass the corresponding class, field name and value. We will reflect it inside the method and instantiate it. Then assign values to the corresponding fields. Because I only use fields. You can add other things. Well. This is fun.
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;}}
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 {/*** is used to assign values to fields of the class, ignoring private and project modifiers, ignore the set/get Method * @ Param C class to be reflected * @ Param ARGs class field names and values separated by commas (,) * @ return */@ suppresswarnings ("unchecked ") public static object getinstance (Class C, string... ARGs) {try {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 (classnotfoun Dexception e) {e. printstacktrace ();} catch (instantiationexception e) {e. printstacktrace ();} return NULL;} public static void main (string [] ARGs) {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:" + SMS. getdestid ());}}
Console output:
Text message content: test data.
Mobile phone number: 15810022404
Tail: 01201101
Fields. setaccessible (true); may be used by everyone, but what we need to do is to know it.
Looking at the JDK source code is undoubtedly the best way to learn and solve this problem.
Over ~~~