java调用内部类的两种方法

package com.fpi.safety;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TestPrintList {
    
    public static void main(String args[]){
        List<User> testList = new ArrayList<User>();
        List<User2> testList2 = new ArrayList<User2>();
        //一、调用内部类的第一种方式,将内部类声明为static,直接通过总类调用
        testList.add(new TestPrintList.User(3,”tom”));
        testList.add(new TestPrintList.User(4,”jack”));
        testList.add(new TestPrintList.User(5,”lili”));
        User user = null;
        Iterator<User> it = testList.iterator();
        //输出list对象属性的第一种方式,遍历list,得到list中封装的对象,再通过对象获得属性值
        while (it.hasNext()) {
          user = (User)it.next();
          System.out.println(“———“+user.getName());
          System.out.println(“———“+user.getAge());
        }
        
        //二、调用内部类的第二种方式
        TestPrintList testPrintList = new TestPrintList(); // 外部类实例化对象
        TestPrintList.User2 user2 = testPrintList.new User2(4,”jack22″); // 实例化内部类对象
        TestPrintList.User2 user22 = testPrintList.new User2(5,”jack5555″);
        testList2.add(user2);
        testList2.add(user22);
        Iterator<User2> it2 = testList2.iterator();
        //输出list对象属性的第二种方式,遍历list,得到list中封装的对象,再通过类反射输出对象属性
        while (it2.hasNext()) {
            printFieldsValue(it2.next());
        }
    }
    
    static class User{
        int age;
        String name;
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public User(int age,String name){
            this.age = age;
            this.name = name;
        }
    };
    
    class User2{
        int age;
        String name;
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public User2(int age,String name){
            this.age = age;
            this.name = name;
        }
    };
    
     public static void printFieldsValue(Object obj) {
            Field[] fields = obj.getClass().getDeclaredFields();
            try {
                for (Field f : fields) {
                    f.setAccessible(true);
                    System.out.println(f.get(obj));
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
}
 

    原文作者:bird_tp
    原文地址: https://blog.csdn.net/bird_tp/article/details/83792825
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞