Java dynamic creation of injected code, injected into a class or interface and invoked through reflection

Source: Internet
Author: User
Tags readfile

1. The class that will be injected:

/* * File name: Jnautil.java * Copyright: Sunny Technologies Co., Ltd. Copyright YYYY-YYYY, All rights reserved * Description: &lt Description > * Modified by: L.hao * Modified: 2014-11-11 * Tracking Number: < Tracking number > * Revision Number: < change tracking number > * Modified: < content > */package Co M.test;import java.util.arrays;import java.util.list;import Com.fms.xx.model.parambean;import com.sun.jna.Native;/ * * < A sentence function description > * < function Details > * * @author L.hao * @version [version number, 2014-11-11] * @see [Related class/method] * @since [Product/module Version]        This] */public class jnautil{//dll file path public String FilePath;    Public Jnautil (String filePath) {this.filepath = FilePath; } public double[] XT (list<parambean> parameterlist, double[] arr) {clibrary INSTANCE = (clibrary) native.loadlibr  ary (Filepath,clibrary.class);  int num = 0; INSTANCE. XT (Double.valueof (Parameterlist.get (num++). GetParamValue ()), Double.valueof (Parameterlist.get (num++).  GetParamValue ()), Double.valueof (Parameterlist.get (num++). GetParamValue ()), arr); Returnarr;}} 

2. The interface that will be injected

/*\ * File name:  Clibrary.java * Version    rights:  Sunny Technologies Co., Ltd. Copyright yyyy-yyyy, all  rights reserved *  Describe: < description > * Modified by:  L.hao * Modified:  2014-11-11 * Tracking Number:  < tracking number > * Revision number:  < change tracking number > * Modified content :  < Modify content > */package com.test;import com.sun.jna.library;/** * < A word function summary > * < feature details > * *  @ Author  L.hao * @version  [version number, 2014-11-11] * @see  [Related Classes/methods] * @since  [Product/module version] */public interface Clibrary extends library{public      void XT (double flj,double xtt,double flk,double arr[]);}

3, inject dynamic code and invoke

/* * File name: Writejavafile.java * Copyright: Sunny Technologies Co., Ltd. Copyright YYYY-YYYY, All rights reserved * Description : < Description > * Modified by: L.hao * Modified: 2014-11-15 * Tracking Number: < Tracking number > * Revision Number: < change tracking number > * Modified: < content > */pack Age Com.test;import java.io.bufferedreader;import Java.io.file;import java.io.filereader;import java.io.FileWriter; Import Java.io.ioexception;import Java.lang.reflect.constructor;import Java.lang.reflect.method;import Java.util.arraylist;import Java.util.arrays;import Java.util.list;import Java.util.map;import Javax.tools.diagnostic;import Javax.tools.diagnosticcollector;import Javax.tools.javafileobject;import Com.fms.xx.common.functionparam;import com.fms.xx.model.parambean;/** * Write Java File * < function description > * * @author L.hao * @ve rsion [version number, 2014-11-15] * @see [related classes/methods] * @since [Product/Module Version] */public class writejavafile{private static String Filep        Ath = "F:\\workspaces\\myeclipse10\\xxcalculate\\src\\com\\test\\clibrary.java"; Private STatic String filepath_jnautil = "F:\\workspaces\\myeclipse10\\xxcalculate\\src\\com\\test\\jnautil.java"; private static String Chfile = "f:\\soft\\apache-tomcat-7.0.52\\webapps\\xxcalculate\\upload\\141112212749\\        SharedLib.h "; /** < A word function description > * < function Details > * @param args [parameter description] * * @return void [return type description] * @throws Excepti  On * @exception throws [violation type] [violation description] * @see [Class, Class # method, Class # Member] */public static void main (string[] args) throws        Exception {//the path of the current class System.out.println ("Path of the current class:" +new File (""). GetAbsolutePath ());        Create file CreateFile (FilePath);                Read interface clibrary file String clibraryfilecontent = ReadFile (FilePath);        list<functionparam> params = Parsehfile (chfile);        The content to be spliced String appendcontent = spliceclibrarystring (params); Write the file (without stitching if it already exists) if (!clibraryfilecontent.trim (). ReplaceAll ("\\s*", ""). Contains (Appendcontent.trim ().   ReplaceAll ("\\s*", ""))) {         Writestringtofile (FilePath, clibraryfilecontent, appendcontent);                }//Read interface Jnautil file String jnautilfilecontent = ReadFile (filepath_jnautil);        Appendcontent = splicejnautilstring (params); Write the file (without stitching if it already exists) if (!jnautilfilecontent.trim (). ReplaceAll ("\\s*", ""). Contains (Appendcontent.trim (). ReplaceAll ("\\s*", "")))        {Writestringtofile (Filepath_jnautil, jnautilfilecontent, appendcontent);        } String FilePath = "F:\\workspaces\\myeclipse10\\xxcalculate\\src\\com\\test";        String SourceDir = "F:\\workspaces\\myeclipse10\\xxcalculate\\src\\com\\test";                String TargetDir = "f:\\soft\\apache-tomcat-7.0.52\\webapps\\xxcalculate\\web-inf\\classes";        Boolean result = Compiler (FilePath, SourceDir, TargetDir);        list<parambean> parames = new arraylist<parambean> (); Parambean (String Paramcode, String paramname, String paramvalue, string paramtype) paramEs.add (New Parambean ("Flj", "Air density", "0.42", "double"));        Parames.add (New Parambean ("XTT", "Air density", "0.3", "double"));        Parames.add (New Parambean ("FLK", "Air density", "0.2", "double"));        double[] arr = new DOUBLE[4];        Compile successfully, start calculation if (result) {Reflectcall (Parames,arr); }}/** * Reflection call Generated file * < function details > * @param parames * @param arr [parameter description] * @return V OID [Return type description] * @exception throws [violation type] [violation description] * @see [Class, Class # method, Class # Member] */public static void Reflectcall (list& Lt Parambean> parames, double[] arr) {try {constructor<?> conststr = Class.forName ("Co            M.test.jnautil "). Getdeclaredconstructor (New class[] {string.class});            Conststr.setaccessible (TRUE); Object bl = conststr.newinstance (new object[] {"f:\\soft\\apache-tomcat-7.0.52\\webapps\\xxcalculate\\upload\\                        141112212749\\sharedlib.dll "}); Class<?                        Extends object> clazz = Bl.getclass ();                        method = Clazz.getdeclaredmethod ("XT", List.class, Double[].class);            Method.invoke (BL, parames, arr);        System.out.println ("Calculated results:" + arrays.tostring (arr));        } catch (Exception e) {e.printstacktrace (); }}//Create a single file public static Boolean createFile (String filePath) {File File = new file (FilePath        );            if (file.exists ()) {//Determine if the file exists System.out.println ("destination file already exists" + FilePath);            File.delete ();        return false; if (Filepath.endswith (File.separator)) {//Determine if the file is a directory System.out.println ("The destination file cannot be a directory!            ");        return false; } if (!file.getparentfile (). exists ()) {//Determine if the directory where the destination file exists///If the destination file contains a folder that does not exist, create a parent folder Syst EM.OUT.PRINTLN ("The directory where the target file is not present, prepare to create it!")            "); if (!file.Getparentfile (). Mkdirs ()) {//Determine if the directory was created successfully System.out.println ("The directory where the target file was created failed!                ");            return false; }} try {if (File.createnewfile ()) {//Create destination file System.out.printl                N ("Create file succeeded:" + FilePath);            return true; } else {System.out.println ("Failed to create file!                ");            return false;            }} catch (IOException e) {//catch exception e.printstacktrace (); System.out.println ("Failed to create file!            "+ e.getmessage ());        return false; }}/** * Reads the contents of the specified file * reads the contents of the specified file into the StringBuffer * @param filePath * @return [parameter description] * * return String [Return type description] * @exception throws [violation type] [violation description] * @see [Class, Class # method, Class # Member] */public static String READF        Ile (String filePath) {File File = new file (FilePath);        BufferedReader reader = null; StringBuffer sb = NEW StringBuffer ();            try {//system.out.println ("reads the contents of the file in the behavior unit, reads a whole line at a time:");            reader = new BufferedReader (new FileReader (file));            String tempstring = null;            int line = 1; Reads one line at a time until NULL is read into the file end while ((tempstring = Reader.readline ()) = null) {Sb.append (                            tempstring). Append ("\t\n");        } reader.close ();        } catch (Exception e) {e.printstacktrace ();    } return sb.tostring ();  /** * Writes a string to the specified file * Write new content based on existing file contents * @param filePath file path * @param oldcontent already has content * @param    Newcontent New Additions * * @return void [return type description] * @exception throws [violation type] [violation description] * @see [Class, Class # method, Class # member] */ public static void Writestringtofile (String filePath, String oldcontent, String newcontent) {Stri        Ngbuffer Strbuffer = new StringBuffer (); try {Oldcontent = oldcontent.substring (0, Oldcontent.lastindexof ("}"));            Strbuffer.append (oldcontent);            Strbuffer.append (newcontent);            Strbuffer.append ("}");            Open a write file, the second parameter in the constructor true indicates that the file is written in append form FileWriter writer = new FileWriter (FilePath, false);            Writer.write (Strbuffer.tostring ());        Writer.close ();        } catch (IOException e) {e.printstacktrace (); }}/** * File compile * Call Java compiler to compile Java file * @param filePath file path * @param the directory where the SourceDir source file is located * @par      Am TargetDir Destination File directory * * @return Boolean [return type description] * @exception throws [violation type] [violation description] * @see [Class, Class # method, Class # member] */@SuppressWarnings ("Rawtypes") public static Boolean compiler (String FilePath, String SourceDir, S        Tring TargetDir) {Boolean compilerresult = false; try {diagnosticcollector<javafileobject> diagnostics = new Diagnosticcollector<javafilEobject> ();                    Compilerresult = Dynamiccompilerutil.compiler (FilePath, SourceDir, TargetDir,            Diagnostics);            if (Compilerresult) {System.out.println ("compile succeeded");                } else {System.out.println ("compilation Failed"); For (Diagnostic diagnostic:diagnostics.getDiagnostics ()) {System.out.println (diagnost                Ic.getmessage (null));        }}} catch (Exception e) {e.printstacktrace ();    } return Compilerresult; }/** * < A sentence function description > * < function Details > * @param fileName * @return [parameter description] * @return Li st<functionparam> [Return type description] * @exception throws [violation type] [violation description] * @see [Class, Class # method, Class # Member] */public static Li St<functionparam> parsehfile (String fileName) {map<string, list<functionparam>> map = Readhfile.parseh (fileName);                list<functionparam> params = (list<functionparam>) map.get ("params");    return params; }/** * Splicing interface file Contents * < function Detail Description > * @param params * @return [parameter description] * * @return String [Return class Type description] * @exception throws [violation type] [description of violation] * @see [Class, Class # method, Class # Member] */public static String spliceclibrarystring (Li        st<functionparam> params) {StringBuffer Strbuffer = new StringBuffer ();        Strbuffer.append ("public void");        Strbuffer.append (Params.get (0). Getmethodname ()). Append ("(");                    for (Functionparam functionparam:params) {strbuffer.append (Functionparam.getparamtype ())        . Append (""). Append (Functionparam.getparamname ()). Append (",");        } strbuffer.replace (Strbuffer.length ()-1, Strbuffer.length (), ""); Strbuffer.append (");").        Append ("\t\n"); return sTrbuffer.tostring (); }/** * Splicing called class contents * < function Details > * @param params * @return [parameter description] * * @return String [Return class Type description] * @exception throws [violation type] [description of violation] * @see [Class, Class # method, Class # Member] */public static String splicejnautilstring (Lis        t<functionparam> params) {String methodName = params.get (0). Getmethodname ();        StringBuffer strbuffer = new StringBuffer ();        Strbuffer.append ("public double[]");                Strbuffer.append (MethodName). Append ("(List<parambean> parameterlist, double[] arr)")        . Append ("\t\n");        Strbuffer.append ("{"). Append ("\t\n");                Strbuffer.append ("Clibrary INSTANCE = (clibrary) native.loadlibrary (Filepath,clibrary.class);")        . Append ("\t\n"); Strbuffer.append ("int num = 0;").        Append ("\t\n"); Strbuffer.append ("INSTANCE.").                Append (MethodName). Append ("(");                int count = Params.size ();        int num = 0; for (FuncTionparam functionparam:params) {num++;            if (count = = num) {continue;    } if ("Double". Equalsignorecase (Functionparam.getparamtype ())) {Strbuffer.append ("            Double.valueof (Parameterlist.get (num++). GetParamValue ()), "). Append (" \t\n ");    } if ("Char". Equalsignorecase (Functionparam.getparamtype ())) {Strbuffer.append ("            Parameterlist.get (num++). GetParamValue (). ToCharArray (), "). Append (" \t\n "); }} strbuffer.append ("arr);").        Append ("\t\n"); Strbuffer.append ("return arr;").        Append ("\t\n");        Strbuffer.append ("}"). Append ("\t\n");    return strbuffer.tostring (); }}


Java dynamic creation of injected code, injected into a class or interface and invoked through reflection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.