Package com.jhl.jvm.lesson8;
Import Java.lang.reflect.Field;
/**
*
* @author JHL
* Java reflection dynamically sets values based on attributes demo
*
*/
public class Exceptionlog {
Private String Exceptionlogid;
Private String ProcessingType;
Private String type;
Private String content;
Public String Getexceptionlogid () {return exceptionlogid;} public void Setexceptionlogid (String exceptionlogid) {this.exceptionlogid = Exceptionlogid;} Public String Getprocessingtype () {return processingtype;} public void Setprocessingtype (String processingtype) {this.processingtype = ProcessingType;} Public String GetType () {return type;} public void SetType (String type) {this.type = type;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;} @SuppressWarnings ("Rawtypes") public static void main (string[] args) throws Exception {String Exceptioninfo = "Processi Ngtype= "+" refueling! "+" #type = "+" "+" #content = "+" Zolan "+" #processingType = "+" 11111 "+" #recordType = "; Exceptionlog Exceptionlog = new Exceptionlog (); Class cls = Exceptionlog.getclass (); string[] str = exceptioninfo.split ("#"); String log = "";//Logging with for (string s:str) {string key = S.split ("=") [0]; if ("RecordType". Equals (key)) log = key; String value = s.split ("="). length > 1? S.split ("=") [1]: "; For (Field Field:cls.getDeclaredFields ()) {if (Field.getname (). Equals (key)) {field = Cls.get Declaredfield (key); Field.setaccessible (TRUE); Field.set (exceptionlog, value);//dynamic set value break; }}} System.out.println ("log=" + log); System.out.println ("exceptionlogid=" + Exceptionlog.getexceptionlogid ()); System.out.println ("content=" + exceptionlog.getcontent ()); System.out.println ("processingtype=" + Exceptionlog.getprocessingtype ()); System.out.println ("type=" + Exceptionlog.gettype ());}
}
Java reflection dynamically sets values based on attributes