首页 > 编程语言 >Java基础-反射

Java基础-反射

时间:2023-02-07 11:57:17浏览次数:45  
标签:反射 Java int 基础 System class println public out

Class类对象的获取

  • 根据类名:类名.class
  • 根据对象:对象.getClass()
  • 根据全限定类名:Class.forName(全限定类名)

例子

interface I1 {
}

interface I2 {
}

class Cell {
    public int mCellPublic;
}

class Animal extends Cell {
    private int privateField;
    public int publicField;
    protected int protectedField;
    int defaultField;

    private static int privateStaticField;
    public static int publicStaticField;
    protected static int protectedStaticField;
    static int defaultStaticField;
}

class Dog extends Animal implements I1, I2 {
    private int dogPrivate;
    public int dogPublic;
    protected int dogProtected;
    int dogDefault;

    private static int dogStaticPrivate;
    public static int dogStaticPublic;
    protected static int dogStaticProtected;
    static int dogStaticDefault;
}

public class TestReflect {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Class<Dog> dog = Dog.class;

        // 类名
        System.out.println(dog.getName()); // com.afabao.learn.sys.Dog
        System.out.println(dog.getSimpleName()); // Dog
        System.out.println(dog.getCanonicalName()); // com.afabao.learn.sys.Dog

        // 接口
        System.out.println(dog.isInterface()); // false
        for (Class<?> anInterface : dog.getInterfaces()) {
            System.out.println(anInterface);
            // interface com.afabao.learn.sys.I1
            // interface com.afabao.learn.sys.I2
        }

        // 父类
        System.out.println(dog.getSuperclass()); // class com.afabao.learn.sys.Animal

        // 创建对象
        Dog d = dog.newInstance();

        // 字段
        for (Field field : dog.getFields()) {
            System.out.println(field.getName());
            // dogPublic
            // dogStaticPublic
            // publicField
            // publicStaticField
            // mCellPublic
        }

        for (Field declaredField : dog.getDeclaredFields()) {
            System.out.println(declaredField.getName());
            // dogPrivate
            // dogPublic
            // dogProtected
            // dogDefault
            // dogStaticPrivate
            // dogStaticPublic
            // dogStaticProtected
            // dogStaticDefault
        }
    }
}

getName

public class TestGetName {
    private class inner {
    }

    public static void main(String[] args) {
        System.out.println(TestGetName.class.getName()); // com.afabao.learn.sys.TestGetName
        System.out.println(TestGetName.class.getSimpleName()); // TestGetName
        System.out.println(TestGetName.class.getCanonicalName());// com.afabao.learn.sys.TestGetName

        System.out.println(inner.class.getName()); // com.afabao.learn.sys.TestGetName$inner
        System.out.println(inner.class.getSimpleName()); // inner
        System.out.println(inner.class.getCanonicalName()); // com.afabao.learn.sys.TestGetName.inner

        System.out.println(args.getClass().getName()); // [Ljava.lang.String;
        System.out.println(args.getClass().getSimpleName()); // String[]
        System.out.println(args.getClass().getCanonicalName()); // java.lang.String[]
    }
}

Constructor

class Info {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Info() {
        super();
    }

    public Info(String name) {
        super();
        this.name = name;
    }

    private Info(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Info{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class TestConstructor {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<Info> infoClass = Info.class;
        Info info = infoClass.newInstance();
        info.setName("Jack");
        info.setAge(20);
        System.out.println(info); // Info{name='Jack', age=20}

        Constructor<Info> constructor1 = infoClass.getConstructor(String.class);
        Info info1 = constructor1.newInstance("哥哥");
        info1.setAge(22);
        System.out.println(info1); // Info{name='哥哥', age=22}

        // 获取私有构造函数方法
        Constructor<Info> constructor2 = infoClass.getDeclaredConstructor(String.class, int.class);
        constructor2.setAccessible(true);
        Info info2 = constructor2.newInstance("姐姐", 30);
        System.out.println(info2); // Info{name='姐姐', age=30}

        Constructor<?>[] declaredConstructors = infoClass.getDeclaredConstructors();
        for (int i = 0; i < declaredConstructors.length; i++) {
            Class<?>[] parameterTypes = declaredConstructors[i].getParameterTypes();
            System.out.println("构造函数[" + i + "] : " + declaredConstructors[i]);
            System.out.print("参数[" + i + "] : (");
            for (int j = 0; j < parameterTypes.length; j++) {
                if(j == parameterTypes.length - 1) {
                    System.out.print(parameterTypes[j].getName());
                } else {
                    System.out.print(parameterTypes[j].getName() + ",");
                }
            }
            System.out.println(")");
        }
        // 构造函数[0] : public com.afabao.learn.sys.Info(java.lang.String)
        // 参数[0] : (java.lang.String)
        // 构造函数[1] : public com.afabao.learn.sys.Info()
        // 参数[1] : ()
        // 构造函数[2] : private com.afabao.learn.sys.Info(java.lang.String,int)
        // 参数[2] : (java.lang.String,int)

        // 获取构造函数的类
        Class<Info> declaringClass = constructor2.getDeclaringClass();
        System.out.println(declaringClass.getName()); // com.afabao.learn.sys.Info

        // 获取构造函数的形参
        Type[] types = constructor2.getGenericParameterTypes();
        for (Type type : types) {
            System.out.println(type.getTypeName());
            // java.lang.String
            // int
        }

        Class<?>[] parameterTypes = constructor2.getParameterTypes();
        for (Class<?> parameterType : parameterTypes) {
            System.out.println(parameterType.getName());
            // java.lang.String
            // int
        }

        System.out.println(constructor2.getName()); // com.afabao.learn.sys.Info

        System.out.println(constructor2.toGenericString()); // private com.afabao.learn.sys.Info(java.lang.String,int)
    }
}

Field

public class TestField {
    public static void main(String[] args) throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        // getField 获取类的public字段(包含父类)
        Class<Student> studentClass = Student.class;
        Field age = studentClass.getField("age");
        System.out.println(age); // public int com.afabao.learn.sys.Person.age

        Field[] fields = studentClass.getFields();
        for (Field field : fields) {
            // 获取定义字段的类
            System.out.println(field.getDeclaringClass());
            // class com.afabao.learn.sys.Student
            // class com.afabao.learn.sys.Person
            // class com.afabao.learn.sys.Person
        }

        // getDeclaredFields, 获取类的所有字段(不包含父类)
        Field[] declaredFields = studentClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField.getDeclaringClass());
            // class com.afabao.learn.sys.Student
            // class com.afabao.learn.sys.Student
        }

        Field desc = studentClass.getField("desc");
        System.out.println(desc); // public java.lang.String com.afabao.learn.sys.Student.desc

        Student student = studentClass.newInstance();
        Field name = studentClass.getField("name");
        name.set(student, "Rose");

        Field age1 = studentClass.getField("age");
        age1.set(student, 38);

        Field desc1 = studentClass.getField("desc");
        desc1.set(student, "不可描述");

        Field score = studentClass.getDeclaredField("score");
        score.setAccessible(true);
        score.set(student, 98);

        System.out.println(student); // Student{desc='不可描述', score=98, name='Rose', age=38}
        System.out.println(score.get(student));
    }
}

@Data
class Person{
    public String name;
    public int age;
}

@Data
class Student extends Person{
    public String desc;
    private int score;

    @Override
    public String toString() {
        return "Student{" +
                "desc='" + desc + '\'' +
                ", score=" + score +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Method

public class TestMethod {
    public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<Circle> circleClass = Circle.class;
        Method drawMethod = circleClass.getMethod("draw", int.class, String.class);
        System.out.println(drawMethod); // public void com.afabao.learn.sys.Shape.draw(int,java.lang.String)

        for (Method method : circleClass.getMethods()) {
            System.out.println(method);
            //public void com.afabao.learn.sys.Shape.draw(int,java.lang.String)
            //public int com.afabao.learn.sys.Circle.getCount()
            //public void com.afabao.learn.sys.Shape.draw()
            //public void com.afabao.learn.sys.Shape.draw(int,java.lang.String)
            //public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
            //public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
            //public final void java.lang.Object.wait() throws java.lang.InterruptedException
            //public boolean java.lang.Object.equals(java.lang.Object)
            //public java.lang.String java.lang.Object.toString()
            //public native int java.lang.Object.hashCode()
            //public final native java.lang.Class java.lang.Object.getClass()
            //public final native void java.lang.Object.notify()
            //public final native void java.lang.Object.notifyAll()
        }

        Method drawCircle = circleClass.getDeclaredMethod("drawCircle");
        System.out.println(drawCircle); // private void com.afabao.learn.sys.Circle.drawCircle()

        Method[] declaredMethods = circleClass.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
            //private void com.afabao.learn.sys.Circle.drawCircle()
            //public int com.afabao.learn.sys.Circle.getCount()
        }

        Circle circle = circleClass.newInstance();
        drawMethod.invoke(circle, 1, "Circle");// draw:Circle: count:1

        drawCircle.setAccessible(true);
        drawCircle.invoke(circle); // drawCircle

        Method getCount = circleClass.getMethod("getCount");
        int count = (int)getCount.invoke(circle);
        System.out.println(count); // 100

    }
}

class Shape {
    public void draw() {
        System.out.println("draw");
    }

    public void draw(int count, String name) {
        System.out.println("draw:" + name + ": count:" + count);
    }
}

class Circle extends Shape {
    private void drawCircle() {
        System.out.println("drawCircle");
    }

    public int getCount() {
        return 100;
    }
}

标签:反射,Java,int,基础,System,class,println,public,out
From: https://www.cnblogs.com/afabao/p/17097878.html

相关文章

  • JavaScript 使用 !! 运算符的利弊
    !!运算符是在JavaScript中将一个值转换为布尔值的常用方法。使用这个运算符的优点是:简单易用:它只需要一行代码就可以完成转换,而不需要使用其他的方法。可读性:它很......
  • java中注解的使用
    1、注解是一种能被添加到java源代码中的元数据,方法、类、参数和包都可以用注解来修饰。注解可以看作是一种特殊的标记,可以用在方法、类、参数和包上,程序在编译或者运行时可......
  • javaScript - String对象的创建,全部属性,常用方法,全部方法
    1.String对象的创建//方式1字面量方式varstr="levi";//方式2创建对象方式varstr=newString("levi"); 2.String对象的属性:属性描述constructor对创建......
  • java List转换为字符串的几种方法
    List转String(用分隔符隔开)使用for循环+StringBuilder的方式就不记了,写一种相对简约一点的做法:publicStringlistToString(Listlist,charseparator){......
  • Mysql基础知识
    查看mysql数据库存放位置showvariableslike'datadir';可以看到,共有三个文件,这三个文件分别代表着:db.opt,用来存储当前数据库的默认字符集和字符校验规则。t_or......
  • Java中进行单元测试junit.Assert断言、Mockito模拟对象、verify验证模拟结果、Java8中
    场景Java8新特性-Stream对集合进行操作的常用API:​​Java8新特性-Stream对集合进行操作的常用API_霸道流氓气质的博客-博客_javalist.stream​​在上面使用流操作时需要用到......
  • 最小化CentOS安装基础命令
    yum-yinstallwgetvimnet-toolszipunziplsoflrzszlsofbridge-utilstree\gccgcc-c++automakepcrepcre-develzlibzlib-devel\nt......
  • QML教程(七) JavaScript
    目录一、对属性值使用JavaScript表达式二、在QML中添加JavaScript函数三、使用JavaScript文件四、属性绑定中的JavaScript五、信号处理程序中的JavaScript......
  • javaFX的几个新特性,让swing彻底过时
    首先声明,Java的GUI曾经是最弱的一环,毋庸置疑,而且历史上因为跟M$的斗争,导致Java失去了Desktop发展的最佳时间点,即便后来SUN&Oracle推出了JavaFX,Desktop......
  • QML概念及框架--继承JavaScript
    QML推荐使用属性绑定和现有的QML元素来创建界面。为了允许执行更高级的行为,QML紧密集成了必要的JavaScript代码。QML中提供的JavaScript环境比在网页浏览器中的更严格。在Q......