• <nav id="wkkge"><strong id="wkkge"></strong></nav>
  • <menu id="wkkge"></menu>
  • Java面向對象
    Java異常
    Java數組
    Java常用類
    Java集合
    Java IO流
    Java線程
    Java反射
    Socket編程
    Java注解開發
    Java GoF設計模式
    HashMap
    Java內存模型
    Java線性表

    Java反射創建實例

     

     

    package com.wkcto.chapter08.demo02;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    
    /**
     * 通過反射創建對象(創建實例)
     * 		newInstance()
     * 
     * @author 蛙課網
     *
     */
    public class Test01 {
    
    	public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
    		//1) 創建Class對象
    		Class<?> class1 = Person.class;
    		
    		//2) 直接通過Class對象創建實例,會調用類的無參構造方法,如果沒有無參構造,則實例化異常
    		Object obj1 = class1.newInstance();
    		System.out.println( obj1 );  	//調用對象的toString()	
    		
    		//3)通過構造方法創建實例
    		//3.1 反射構造方法Person(String, int, String)
    		Constructor<?> constructor = class1.getConstructor(String.class, int.class, String.class);
    		
    		//3.2通過構造方法 創建實例, 調用newInstance()方法,傳遞構造方法的實參
    		Object obj2 = constructor.newInstance("lisi", 18,"男");    //new Person("lisi", 18,"男")
    		System.out.println( obj2 );
    		
    		
    	}
    
    }

     

    package com.wkcto.chapter08.demo02;
    
    public class Person {
    	public String name;
    	int age;
    	private String gender;
    	static String country = "中國";
    	
    	public Person() {
    		System.out.println("Person類的無參構造方法");
    	}
    
    	public Person(String name, int age, String gender) {
    		System.out.println("Person類的有三個參數的構造方法");
    		this.name = name;
    		this.age = age;
    		this.gender = gender;
    	}
    	
    	public void set(String name, int age, String gender) {
    		this.name = name;
    		this.age = age;
    		this.gender = gender;
    	}
    
    	@Override
    	public String toString() {
    		return "Person [name=" + name + ", age=" + age + ", gender=" + gender + "]";
    	}
    		
    }

     

    全部教程
  • <nav id="wkkge"><strong id="wkkge"></strong></nav>
  • <menu id="wkkge"></menu>
  • 面对面棋牌游戏