Advertisement
Swampert420

Untitled

Jul 25th, 2022
957
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. package package1;
  2. import java.lang.reflect.Constructor;
  3. import java.lang.reflect.Method;
  4.  
  5. class Student {
  6.     int a;
  7.     int b;
  8.    
  9. //    public Student(int a, int b){
  10. //        this.a = a;
  11. //        this.b = b;
  12. //    }
  13.    
  14. //    public int getA(){
  15. //        return a;
  16. //    }
  17. //    
  18. //    public int getB(){
  19. //        return b;
  20. //    }
  21.    
  22.     public Student(){
  23.         a= 5;
  24.         b= 10;
  25.     }
  26.    
  27.     public void print(){
  28.         System.out.println(a+b);
  29.     }
  30. }
  31. public class MainClass {
  32.  
  33.     public static void main(String[] args) {
  34.          Student st;
  35.         try {
  36.             st = Student.class.newInstance();
  37.             st.print();
  38.            
  39.             Constructor <Student> constructor = Student.class.getConstructor();
  40.             Student student = constructor.newInstance();
  41.             student.print();
  42.             Class cls = Class.forName("package1.Student");
  43.             Constructor con = cls.getConstructor();
  44.             Object obj = con.newInstance();
  45. //            Class cl = Class.forName("Student");
  46. //            Class type[] = {int.class, int.class};
  47. //            Constructor cons = cl.getConstructor(type);
  48. //            Object newInstanceObject = cons.newInstance(22, 35);
  49. //            Student st = (Student) newInstanceObject;
  50. //            st.print();
  51. //            Constructor c = Class.forName("Student").getConstructor(new Class[]{int.class, int.class});
  52. //            Student st2 = (Student)c.newInstance(45, 55);
  53. //            System.out.println(st2.getA());
  54.             Method methods[] = cls.getDeclaredMethods();
  55.             for (Method method : methods) {
  56.                 method.invoke(obj);
  57.             }
  58.            
  59.         }catch (Exception e) {
  60.             e.printStackTrace();
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement