Created
March 23, 2018 12:35
-
-
Save AhianZhang/68dbcc3271f3d2f31e6de1c1d74cc65e to your computer and use it in GitHub Desktop.
java 反射的实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test; | |
import java.lang.reflect.Constructor; | |
import java.lang.reflect.InvocationTargetException; | |
/** | |
* Created by AhianZhang on 2018/3/23. | |
*/ | |
public class reflect | |
{ | |
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException | |
{ | |
Foo foo = new Foo(); | |
Class cls1 = foo.getClass();//第一种 | |
System.out.println("getClass()输出的结果为:" + cls1); | |
Class cls2 = Foo.class;//第二种 | |
System.out.println("对象实例化输出的结果为:" + cls2); | |
Class cls3 = Class.forName("com.test.Foo");//第三种,需要抛出异常 | |
System.out.println("foName()方式输出的结果为:"+cls3); | |
Object obj = cls1.newInstance();//默认加载无参构造方法,如果没有无参构造方法则会抛出 InstantiationException 异常 | |
Constructor constructor =cls1.getConstructor(String.class);//获取构造参数 | |
Object obj1 = constructor.newInstance("sam");//通过构造器对象进行初始化 | |
} | |
} | |
class Foo | |
{ | |
public String name; | |
public Foo(){ | |
System.out.println("这是无参构造"); | |
} | |
public Foo(String name){ | |
System.out.println("Hello"+name); | |
} | |
public String setName() | |
{ | |
return name; | |
} | |
public void getName(String name) | |
{ | |
this.name = name; | |
} | |
@Override | |
public String toString() | |
{ | |
return "Foo{" + | |
"name='" + name + '\'' + | |
'}'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这是无参构造
getClass()输出的结果为:class com.test.Foo
对象实例化输出的结果为:class com.test.Foo
foName()方式输出的结果为:class com.test.Foo
这是无参构造
Hellosam