Java Reflection Attributes HackerRank Solution

Hello Programmers, In this post, you will know how to solve the Java Reflection Attributes HackerRank Solution. This problem is a part of the HackerRank Java Programming Series.

Java Reflection Attributes HackerRank Solution
Java Reflection Attributes HackerRank Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Java Reflection Attributes HackerRank Solution

Ezoicreport this adObjective

JAVA reflection is a very powerful tool to inspect the attributes of a class in runtime. For example, we can retrieve the list of public fields of a class using getDeclaredMethods().

In this problem, you will be given a class Solution in the editor. You have to fill in the incompleted lines so that it prints all the methods of another class called Student in alphabetical order. We will append your code with the Student class before running it. The Student class looks like this:

class Student{
    private String name;
    private String id;
    private String email;
    public String getName() {
        return name;
    }
    public void setId(String id) {
        this.id = id;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void anothermethod(){  }
    ......
    ......
    some more methods
    ......
}

You have to print all the methods of the student class in alphabetical order like this:

anothermethod
getName
setEmail
setId
......
......
some more methods
......

There is no sample input/output for this problem. If you press “Run Code”, it will compile it, but it won’t show any outputs.

Hint: See the oracle docs for more details about JAVA Reflection Methods and Fields

Java Reflection Attributes HackerRank Solutions

public class Solution {
    public static void main(String[] args) {
        Class student = Student.class; // uses class literal, not a function.
        Method[] methods = student.getDeclaredMethods();
        /* Get names from Methods */
        ArrayList<String> methodNames = new ArrayList();
        for (Method method : methods) {
            methodNames.add(method.getName());
        }
        /* Sort and print names */
        Collections.sort(methodNames);
        for (String name: methodNames) {
            System.out.println(name);
        }
    }
}

Disclaimer: The above Problem (Java Reflection Attributes) is generated by Hackerrank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Can You Access HackerRank Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad