отображение имени классов, которые выполняет компилятор Java - PullRequest
0 голосов
/ 26 июня 2019

Я работаю над проектом, который содержит много пакетов, и каждый пакет содержит много классов. когда я запускаю класс, который содержит метод main, я не знаю, какой класс на самом деле выполняется и участвует в моей работе. есть ли способ, которым я могу отследить, какие классы посещал компилятор, или есть какой-либо код, который я могу поместить в конец основного метода, который показывает имя классов, которые были выполнены.

Я пытался найти свойства компилятора, которые помогают мне отслеживать его путь, но я не нашел ничего

Я использую Eclipse

1 Ответ

0 голосов
/ 26 июня 2019

Это на самом деле то, что называется отражением. Есть методы, которые вы можете запустить, чтобы увидеть все ваши классы Java в вашем проекте. Несмотря на то, что я сам не знаю, как увидеть все классы, которые запускаются в конкретном прогоне, вы можете видеть все классы в вашем проекте каждый раз, когда вы запускаете с отражением, и я уверен, что есть способ использовать его для того, что вы делаете хотят.

Прочитайте документацию Reflection и добавьте небольшой фрагмент, который покажет вам, как вы можете использовать Reflection для просмотра многих вещей, таких как Методы / Классы, и многих других вещей в вашем Java-проекте.

// Creating object whose property is to be checked 
        Test obj = new Test(); 

        // Creating class object from the object using 
        // getclass method 
        Class cls = obj.getClass(); 
        System.out.println("The name of class is " + 
                            cls.getName()); 

        // Getting the constructor of the class through the 
        // object of the class 
        Constructor constructor = cls.getConstructor(); 
        System.out.println("The name of constructor is " + 
                            constructor.getName()); 

        System.out.println("The public methods of class are : "); 

        // Getting methods of the class through the object 
        // of the class by using getMethods 
        Method[] methods = cls.getMethods(); 

        // Printing method names 
        for (Method method:methods) 
            System.out.println(method.getName()); 

        // creates object of desired method by providing the 
        // method name and parameter class as arguments to 
        // the getDeclaredMethod 
        Method methodcall1 = cls.getDeclaredMethod("method2", 
                                                 int.class); 

        // invokes the method at runtime 
        methodcall1.invoke(obj, 19); 

        // creates object of the desired field by providing 
        // the name of field as argument to the  
        // getDeclaredField method 
        Field field = cls.getDeclaredField("s"); 

        // allows the object to access the field irrespective 
        // of the access specifier used with the field 
        field.setAccessible(true); 

        // takes object and the new value to be assigned 
        // to the field as arguments 
        field.set(obj, "JAVA"); 

        // Creates object of desired method by providing the 
        // method name as argument to the getDeclaredMethod 
        Method methodcall2 = cls.getDeclaredMethod("method1"); 

        // invokes the method at runtime 
        methodcall2.invoke(obj); 

        // Creates object of the desired method by providing 
        // the name of method as argument to the  
        // getDeclaredMethod method 
        Method methodcall3 = cls.getDeclaredMethod("method3"); 

        // allows the object to access the method irrespective  
        // of the access specifier used with the method 
        methodcall3.setAccessible(true); 

        // invokes the method at runtime 
        methodcall3.invoke(obj); 

и вывод этого:

The name of class is Test
The name of constructor is Test
The public methods of class are : 
method2
method1
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
The number is 19
The string is JAVA
Private method invoked

Есть две неудачи для отражения:

Машине нужно время, чтобы обработать ее, как и все остальное в вашем коде. Он выставляет внутренние методы и класс, поэтому я бы рекомендовал делать это только для тестирования и просмотра того, что вы хотите увидеть, а затем его удаления.

Надеюсь, это поставит вас на правильный путь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...