How to use java annotations to modify source code before final compilation?

前端 未结 4 914
不思量自难忘°
不思量自难忘° 2021-02-20 07:52

I\'ve read from the apt tool page that one can create AnnotationProcessors to generate new derived files (source files, class files, deployment descriptors, etc.). I am looking

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-20 08:40

    When I am going to generate the version for distribution it, I have a class that override all the constants with the Ofuscated String call:

    This is the process:

    1. I run my ANT, that copy all the code in other place.
    2. The ANT call to OfuscateJavaConstant.
    3. I Compile the code.

    The ANT:

     
         
         
             
             
         
      
    

    The Java Ofuscate code (ObfuscatedString):

    public static void main(String[] args) {
        if ( args!=null ){
            String[] ficheros = args[0].split(";");
    
            if ( args!=ficheros )
                for (String ruta:ficheros)
                    ofuscateConstantClass( ruta );
        }
    }
    
    private static void ofuscateConstantClass( String fileName ){
    
        File archivo = null;
        FileReader fr = null;
        BufferedReader br = null;
        List sb  = new ArrayList();
        FileWriter fichero = null;
        PrintWriter pw = null;
    
        try{
            archivo = new File( fileName );
            fr = new FileReader (archivo);
            br = new BufferedReader(fr);
            String linea;
            while( (linea=br.readLine())!=null ){
    
                String noWhite = linea.trim().replaceAll(" +", " ");
    
                if ( noWhite.toLowerCase().startsWith("public static final string") && noWhite.endsWith("\";") ){
    
                    String firstPart = noWhite.substring(0, noWhite.indexOf("\"") );
                    String constant = noWhite.substring(noWhite.indexOf("\"")+1, noWhite.lastIndexOf("\"") );
                    String ofuscatedConstant = obfuscate( constant );
                    String secondPart = noWhite.substring(noWhite.lastIndexOf("\"")+1 );
                    sb.add( firstPart + ofuscatedConstant + secondPart );
                    System.out.println( constant + "-->" + ofuscatedConstant );
                } else
                    sb.add( linea );
            }
    
            fichero = new FileWriter( fileName );
            pw = new PrintWriter(fichero);
            for (String s:sb)
                pw.println( s );
    
        } catch ( Exception e){
    
        } finally {
             try{
                 if( null != fr )
                     fr.close();
                 if( null != pw )
                     pw.close();
                 if( null != fichero )
                     fichero.close();
             }catch (Exception e2){
                e2.printStackTrace();
             }
        }
    
    }
    

    Hope it helps :)

提交回复
热议问题