学习打卡--反射(2)

今天没搞太多东西,只是简单地学习了下Swing、以及知道了可以用反射来调用方法、修改成员属性等

package com.sy.reflection;

public class Student {
        public String name;
        private int age;
        public Student(String name,int age) {
            this.name = name;
            this.age = age;
            }
        public void Print() {
            System.out.println("你妹");
        }
  
}
package com.sy.reflection;
import java.lang.reflect.*;
public class TestStudent {
      public static void main(String[] args)throws Exception {
          Student stu = new Student("张三",18);
          Class<?> c = stu.getClass();//<>表示泛型,?表示不确定类型
         
          //通过反射调用方法
          Method m = c.getMethod("Print", null);
          m.invoke(stu, null);
          
          Field f1 = c.getField("name");//参数为要从类中得到的字段
          String str = (String)f1.get(stu);//参数为要获取的字段值的对象
          System.out.println(str);
          
          Field f2 = c.getDeclaredField("age");
          //因为age为私有,所以要设置安全检查
          f2.setAccessible(true);
          f2.set(stu,20);//通过反射修改属性值
          int Age = (int)f2.get(stu);
          System.out.println(Age);
      }
}
package swing;

import java.awt.*;

import javax.swing.*;

public class jframe {
       public jframe() {
           JFrame f = new JFrame("登录窗口");
           GridLayout g = new GridLayout(3,1);
           JPanel p1 = new JPanel();
           JPanel p2 = new JPanel();
           JPanel p3 = new JPanel();
           JLabel l1 = new JLabel("账号:");
           JLabel l2= new JLabel("密码:");
           JTextField t1 = new JTextField(10);
           JPasswordField pw = new JPasswordField(10);
           pw.setEchoChar('*');
           JButton b1 = new JButton("确定");
           f.setVisible(true);
           f.setSize(400,300);
           f.setLayout(g);
           p1.add(l1);
           p1.add(t1);
           p2.add(l2);
           p2.add(pw);
           p3.add(b1);
           f.add(p1);
           f.add(p2);
           f.add(p3);
       }
       public static void main(String[] args) {
         jframe j = new jframe();
       }
}

猜你喜欢

转载自www.cnblogs.com/susususu/p/10771590.html
今日推荐