dimanche 12 avril 2020

How to get the class variables count of a given.java file?

I need to create an application to get the class variables(attributes) count on a given .java file.So I developed a code using java reflection as below.So in here I create a new .java file with the same content of importing .java file in my src package because then that .java file can be accessible to the reflection purposes.But the problem is IDE is not figuring out the updates of that files automatically,which means even though the file is created already in my directory IDE doesn't figure it out instantly so I need to refresh the src package to notify the updates to the IDE.So how can I solve this issue.Therefor when you run this for first time there will be an exception of class not found exception ,because even though that .java file already there in the src folder IDE doesn't know. I tried with eclipse, Intelij IDES.

  import java.io.FileReader;
  import java.io.FileWriter;
  import java.io.IOException;
  import java.lang.reflect.Field;
  importjava.util.concurrent.atomic.AtomicInteger;


 public class AppInitializer {
public static void main(String args[])throws Exception{
    AtomicInteger atomicInteger = new AtomicInteger();
    Runtime.getRuntime().addShutdownHook(new Thread()
    {
        public void run()
        {
            try {
                meth ();
            } catch (ClassNotFoundException e) {
                e.printStackTrace ( );
            }
        }
    });

    FileReader fr=new FileReader("C:\\Users\\User\\Desktop\\Sample.java");
    int i;
    StringBuffer str= new StringBuffer("");
    while((i=fr.read())!=-1){
    str.append ( (char)i );}

    String s = String.valueOf ( str );


    String replaceString=s.replaceAll ( "public class [^\\n]+", "public class filename{" );
    System.out.println (replaceString );

    fr.close();
    try {
        FileWriter myWriter = new FileWriter("src/filename.java");
        myWriter.write( String.valueOf ( replaceString ) );

        myWriter.close();
        System.out.println("Successfully wrote to the file.");

    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }

}
 static void meth() throws ClassNotFoundException {

    Class classs= Class.forName ( "filename" );
    int count = 0;
    for (Field field : classs.getDeclaredFields ()){
        count++;
    }
    System.out.println (count );
}
}




Aucun commentaire:

Enregistrer un commentaire