zoukankan      html  css  js  c++  java
  • Java -- 反射机制

    实例化对象的两种形式:

    1)通过关键字new

    2)通过反射机制完成

    package test;
    
    //Book类
    class Book {
        private String title;
        private double  price;
        public void setPric(double price) {
            this.price = price;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        @Override
        public String toString() {
            return "图书名称:"+ title + " 价格:" + price;
        }
    }
    
    public class TestReflection {
        public static void main(String[] args) throws Exception {
            Class<?> cls = Class.forName("test.Book"); //包名.类名
            Book book = (Book) cls.newInstance();
            book.setTitle("Java");
            book.setPric(10.01);
            System.out.println(book.toString()); //图书名称:Java 价格:10.01
        }
    }

     Q:如果类中没有提供无参构造方法,只提供了有参构造方法,则必须明确调用指定的构造方法才可以通过反射实例化对象

    package test;
    
    import java.lang.reflect.Constructor;
    
    //Book类
    class Book {
        private String title;
        private double  price;
        public Book(String title,double price){
            this.price = price;
            this.title = title;
        }
        
        
        @Override
        public String toString() {
            return "图书名称:"+ title + " 价格:" + price;
        }
    }
    
    public class TestReflection {
        public static void main(String[] args) throws Exception {
            Class<?> cls = Class.forName("test.Book");
            Constructor<?> cons = cls.getConstructor(String.class,double.class);
            Book book = (Book) cons.newInstance("Java",10.01);
            System.out.println(book.toString());                //图书名称:Java 价格:10.01
        }
    }
    拼命敲
  • 相关阅读:
    Django之信号
    Django缓存
    git简介
    Django request.path
    Django loaction.pathname 属性
    Ajax
    Anaconda 执行命令报ssl错误
    几行代码快速去掉迅雷临时文件的后缀
    win7 64 位安装 python,提示: 0x80240017-未指定的错误
    系统变量 %USERPROFILE%
  • 原文地址:https://www.cnblogs.com/wuyuwuyueping/p/9391636.html
Copyright © 2011-2022 走看看