zoukankan      html  css  js  c++  java
  • 反射

    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    public class FanShe {
    
        public static void main(String[] args) throws Exception {
            // 创建class类实例,常用的有三种方法
            Class<?> clazz1 = Person.class;
            // Class<?> clazz2 =Class.forName("包名.类名"); //有异常
            // Class<?> clazz3 =new Person().getClass();
            // 创建运行时类的实例,如果包含无参构造器
            Object ob1 = clazz1.newInstance();
            // 创建运行时类的实例,如果没有无参构造器
            Constructor<?> con = clazz1.getConstructor(int.class, String.class);
    // Object ob2 =con.newInstance(2,"zhangsan"); //形参还可以用new class[]{int.class,String.class} // 调用指定的属性,如果是public修饰的 Field filed1 = clazz1.getField("number"); System.out.println(filed1.get(ob1)); // 调用指定的属性,如果不是public修饰的 Field filed2 = clazz1.getDeclaredField("age"); // 拼凑方法名,get()方法 String filed = "age"; String getField = "get" + String.valueOf(filed.charAt(0)).toUpperCase() + filed.substring(1); System.out.println(getField); // 拼凑方法名,set()方法 String setField = "set" + filed.toUpperCase().charAt(0) + filed.substring(1); System.out.println(setField); // 调用指定的方法 Method method1 = clazz1.getDeclaredMethod("setAge", new Class[] { int.class }); method1.invoke(ob1, 20); Method method2 = clazz1.getDeclaredMethod(getField); System.out.println(method2.invoke(ob1)); // 如果调用的方法没有返回值,则打印结果除了方法体里的打印内容外,还会打印null // 如果有返回值,则会把null替换成相应的返回值 } } public class Person { public int number =20; private int age; private String name; public Person(int age, String name) { this.age = age; this.name = name; } public Person() { } 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 int speak(){ System.out.println("我是一个人"); return 1; } }
  • 相关阅读:
    EffectiveC#17--装箱和拆箱的最小化
    EffectiveC#16--垃圾最小化
    EffectiveC#15--使用using和try/finally来做资源清理
    NET基础课--对象的筛选和排序(NET之美)
    Objective-C浅拷贝和深拷贝
    IOS viewdidload 方法在 init 方法之前调用
    [iOS]为什么不要在init初始化方法里调用self.view
    为什么init方法里有self.view就会先跑viewdidload方法
    IOS开发中重写init方法使用需谨慎
    The file “XXX.app” couldn’t be opened because you don’t have permission to view it.
  • 原文地址:https://www.cnblogs.com/xieshunjin/p/5506242.html
Copyright © 2011-2022 走看看