mardi 14 novembre 2017

How to use Reflection to check Classes information with specific directory

The goal is to create a program to look into any provided directory and look up class's information using reflection.I should be able to type in terminal:

$ java Reflection /Users/Minh/Desktop/test/ 

It will print out what ever class's information inside test folder such as methods and fields. I have my class path below.

/Users/Minh/WorkSpace/PackageExplorer/src/Reflection.java

public class Reflection {
        public static void main(String[] args) {
            Object s2 = null;
            try {
                s2 = Class.forName(args[0]).newInstance();
                System.out.println("What's my name");
                System.out.println(s2.getClass().getName());
                System.out.println("Can you be simpler?");
                System.out.println(s2.getClass().getSimpleName());
            } catch (Exception e) {
                System.out.println(e);
            }
    }

/Users/Minh/Desktop/test/Student.class

 public class Student {
        private int studentId ;

        Student(){
            studentId = 10000;
        }
        public int getStudentId() {
            return studentId;
        }

        public void setStudentId(int studentId) {
            this.studentId = studentId;
        }
    }

But i got this error

MacBook-Pro-2:src Minh$ java Reflection /Users/Minh/Desktop/test/
java.lang.ClassNotFoundException: /Users/Minh/Desktop/test/
Exception in thread "main" java.lang.NullPointerException
    at Reflection.main(Reflection.java:22)

If i put Student.java and Reflection.java inside the same directory, it works fine but that is not the goal.





Aucun commentaire:

Enregistrer un commentaire