1. 程式人生 > >學習打卡--反射(2)

學習打卡--反射(2)

test jtext frame etc you pack -- grid jpa

今天沒搞太多東西,只是簡單地學習了下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();
       }
}

學習打卡--反射(2)