Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: Java Reflection API

  1. #1
    Junior Member
    Join Date
    Jul 2021
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Java Reflection API

    Please I want to ask: If one wants to inspect classes that are unknown say without instantiating that class. How do I write a dynamic reflection without accepting a fully qualified class name or simple name?

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java Reflection API

    Do you have an specific questions about how to use the classes and methods in the reflect package?
    What have you tried?

    Have you read this: https://www.oracle.com/technical-res...eflection.html
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jul 2021
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Reflection API

    So I created two classes and wrote a code to read them.

    package javareflectionapi;
     
     
    import java.lang.reflect.*;
     
     
     
     
    /**
     *
     * @author
     */
    public class ReflectionAPI {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws NoSuchMethodException {
            // TODO code application logic here
     
            //getting the class
            Class c1 = ClassName.class;
     
            //getting the name of the class
            String class1 = c1.getSimpleName();
            String newClass1 = null;
     
            //Printing the Header
             System.out.println("------------- Classes --------------");
     
            System.out.println("The name of all the Classes are: ");
     
            //Printing the class name
            System.out.println(class1);
     
     
           //getting the class
            Class c2 = AnotherClassName.class;
            String class2 = c2.getSimpleName();
     
            //Printing the class name
              System.out.println(class2);
     
              // Accessing the Modifiers
            int class1Modifiers = c1.getModifiers();
     
            // 
            boolean isPublic = Modifier.isPublic(class1Modifiers);
            boolean isFinal = Modifier.isFinal(class1Modifiers);
            boolean isInterface = Modifier.isInterface(class1Modifiers);
            boolean isAbstract = Modifier.isAbstract(class1Modifiers);
     
            //Printing the Header
            System.out.println("------- Class1  Modifiers --------------");
            // Checking if the modifier is Public
            System.out.println("Is Public? " + isPublic);
            // hecking if the modifier is Final
            System.out.println("Is Final? " + isFinal);
            // hecking if the modifier is Interface
            System.out.println("Is Interface? " + isInterface);
            // hecking if the modifier is Abstract
            System.out.println("Is Abstract? " + isAbstract);
     
     
           //Printing the Header 
           System.out.println("------------ Method 1 --------------");
     
           // Initializing the Method
            Method[] methods1;
     
         methods1 = ClassName.class.getMethods();
        System.out.println("All methods of the " + class1 + " Class are: ");
        for(Method method : methods1){
        System.out.println(method.getName());
          }
     
        System.out.println("------------ Method 2 --------------");
         // Initializing the Method
        Method[] methods2;
        methods2 = AnotherClassName.class.getMethods();
        System.out.println("All methods of the " + class2 + " Class are: ");
        for(Method method : methods2){
        System.out.println(method.getName());
          }
     
     
        System.out.println("----------- Getter & Setter Methods --------------");  
     
               // Initializing the Method
              Method[] methods = c1.getMethods();
     
              // iteratiing through the methods 
              for(Method method : methods){
              boolean isGetter = isGetter(method);
              boolean isSetter = isSetter(method);
     
     
              // printing the getter and setter methods
              System.out.println("Method names are: " + method.getName());
              System.out.println("is Getter?: " + isGetter);
              System.out.println("is Setter?: " + isSetter);
              }
     
     
       System.out.println("----------- Constructor --------------"); 
     
          // Getting the 
            c1 = String.class;
            Constructor specific = null;
     
            try{
                specific = c1.getConstructor(String.class);
     
            }catch(NoSuchMethodException | SecurityException e)
            {
                e.printStackTrace();
            }
     
            Class[] parameter = specific.getParameterTypes();
     
            if(parameter.length == 1 && parameter[0].equals(class1.getClass()))
            {
                try {
                    newClass1 = (String) specific.newInstance(class1);
                } catch (InstantiationException | IllegalAccessException
                        | IllegalArgumentException | InvocationTargetException e)
                {
                            e.printStackTrace();
     
     
     
                }
     
        }
                //Get the constructor name
                System.out.println("Constructor is: "+ newClass1);
     
                //Return the parameter type
                         for(Class para : parameter){
                System.out.println("Parameter Type is: " + para.getName());
            }   
     
                  System.out.println("----------- Fields --------------");            
     
     
     
              //getting private fields
              Class newTourist = Tourist.class;
              Field[] privateFields = newTourist.getDeclaredFields();
     
              for(Field privField : privateFields){
     
              System.out.println("Fields are: " + privField.getName());
              }
     
     
     
     
     
        } 
     
        // Method is getter if names start with get, and no parameters.
        public static boolean isGetter(Method method) {
            if (!method.getName().startsWith("get")) {
                return false;
            }
            if (method.getParameterTypes().length != 0) {
                return false;
            }
            if (void.class.equals(method.getReturnType())) {
                return false;
            }
            return true;
        }
     
     
        // Method is setter if names start with set, and only one parameter.
        public static boolean isSetter(Method method) {
            if (!method.getName().startsWith("set")) {
                return false;
            }
            if (method.getParameterTypes().length != 1) {
                return false;
            }
            return true;
        }
     
     
    }

    What I want to achieve is, using the reflection to inspect any random class objects, (that is not ClassName or AnotherClassName) through a GUI.
    Last edited by Redux23; July 26th, 2021 at 08:18 AM.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java Reflection API

    random class objects
    Where are those located? How does the code access them?
    For example if you have a .class file, will the code read the bytes of the code and parse out its contents?

    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jul 2021
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Reflection API

    The idea was to make my program serve as a plugin that people can add to their codes to inspect their predefined classes. Do not know if it is a good idea.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java Reflection API

    Where are the classes to be inspected located? How will your program access them?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Jul 2021
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Reflection API

    Now, that's my second problem as I do not fully understand the reflection API and I m still learning to use Java. if a .class file is stored in a folder, how do I access that through my program regardless of the location?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java Reflection API

    For simplicity, assume the .class file's location is known. How will the code look at that file?
    Later the FileChooser class can be added to allow the user to find and select the .class file.

    Takee a look at https://docs.oracle.com/javase/7/doc...ows/javap.html
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Jul 2021
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Reflection API

    Initially, like the code above, I created two other classes in the reflection API package itself. That is how it has been looking at the classes. They are all in one .class file.

    I need to create a separate file for the test classes if I am correct, right?

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java Reflection API

    They are all in one .class file.
    What does that mean? I thought there can only be one class in a .class file.

    How does the program access the .class files you want it to inspect?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Jul 2021
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Reflection API

    Okay, so I have 3 files: ClassName, AnotherClassName, and Main which are created in the same Reflection API package. So I inspect the classes from the Main method as the code above does that. The .class file is stored in Users/{sytemName}/NetBeansProject/JavaReflectionAPI and I just run it on the IDE from the Main class. If I get your question right.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java Reflection API

    Thanks. From your answer, I assume the program accesses the class files via the default classpath set when the program executes.

    How does that arrangement satisfy your requirements: using the reflection to inspect any random class?
    The code has hardcoded the class names instead of having the class names come from a variable.

    The Class class has a method that returns the Class object associated with the class or interface with the given string name.
    Take a look at the API doc for the Class class.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Jul 2021
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Reflection API

    Okay, thanks it helps. If I have any more questions can I ask on here or create a new forum for it?

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java Reflection API

    Continue here if on the same program and problem.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Jul 2021
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Reflection API

    Thanks.

Similar Threads

  1. Java Reflection question
    By gunitinug in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 1st, 2017, 03:24 AM
  2. Reflection
    By lightOfDay in forum Object Oriented Programming
    Replies: 6
    Last Post: August 26th, 2012, 08:35 PM
  3. [SOLVED] Java Reflection, laoding external classes and casting
    By ashenwolf in forum Java Theory & Questions
    Replies: 3
    Last Post: May 10th, 2011, 12:33 PM
  4. [SOLVED] java Reflection Question - I am lost.
    By prain in forum Java Theory & Questions
    Replies: 3
    Last Post: May 13th, 2010, 02:43 PM