反射及构造函数

package com.gxnu.study.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.stream.Stream;

import org.junit.Test;

import com.gxnu.study.reflect.bean.Person;

public class ReflectEx {
@Test
public void testMethod(){
Class<Person> clazz = Person.class;
Method[] methods = clazz.getDeclaredMethods();
Stream.of(methods).forEach(m->{
System.out.println(m.getName());
System.out.println(m.getModifiers());

int modifier = m.getModifiers();
if((modifier & Modifier.ABSTRACT) == Modifier.ABSTRACT){
System.out.println("abstract");
}
if((modifier & Modifier.PUBLIC) == Modifier.PUBLIC){
System.out.println("public");
}
});
}

@Test
public void testPublicMethod(){
try {
Stream.of(Class.forName("com.gxnu.study.reflect.bean.Person").getMethods()).forEach(System.out::println);
//7-21.src.com.gxnu.study.reflect.bean.Person

} catch (SecurityException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Test
public void testInvoke(){
Class clazz = Person.class;
Person p = null;
try {
p = (Person) clazz.newInstance();
Method m = clazz.getMethod("getName");
String obj = (String) m.invoke(p);
System.out.println(obj);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException
| IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("**************");

try {
Method m1 = clazz.getMethod("get", int.class, double.class, String.class);
String[] res = (String[]) m1.invoke(p, 1, 77_989_900_7.1e-7,"ming");
Stream.of(res).forEach(System.out::println);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


@Test
public void testConstructor(){
Class<Person> clazz = Person.class;//预先加载到内存
//Class<?> clazz2 = clazz.forName("");//动态加载
Person p = null;
try {
Constructor<Person> cons = clazz.getConstructor();
p = (Person) cons.newInstance();
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(p);

String str = "java.lang.String";
Person p2 = null;
try {
Class classStr = Class.forName(str);
Constructor con2 = clazz.getConstructor(String.class,double.class);
p2 = (Person) con2.newInstance("lisi",2.);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(p2);

}

}

posted @ 2018-07-21 21:59  智敏罗  阅读(134)  评论(0编辑  收藏  举报