In Java, reflection allows us to inspect and manipulate classes, interfaces, constructors, methods, and fields at runtime. This program demonstrates the use of reflection to interact with a Student class. The Student class has several methods, including getters and setters for name, id, and email, as well as an additional method.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The program first gets the Class object of the Student instance. It then retrieves all declared methods of the Student class using the getDeclaredMethods() method. These method names are added to an ArrayList. The ArrayList is sorted in alphabetical order using the Collections.sort() method. Finally, the program iterates over the sorted list and prints out each method name.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.advanced;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
/**
*
*/
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() {
}
}
public class JavaReflectionAttributes {
public static void main(String[] args) {
Class student = new Student().getClass();
Method[] methods = student.getDeclaredMethods();
ArrayList methodList = new ArrayList<>();
for (Method m : methods) {
methodList.add(m.getName());
}
Collections.sort(methodList);
for (String name : methodList) {
System.out.println(name);
}
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.