标签:dex 允许 illegal strong tcl declared 运行时 参数 common
java反射就是通过字节码文件,创建对象,获取类的相关信息
反射获取Class的四种方式
1.调用运行时类本身的.class属性
Class clazz = String.class;
2,通过运行时类的对象获取
Person p = new Person();
Class clazz = p.getClass();
3.通过Class的静态方法获取:体现反射的动态性
String className = “java.util.commons”;
Class clazz = Class.forName(className);
4.通过类的加载器
String className = “java.util.commons”;
ClassLoader classLoader = this.getClass().getClassLoader();
Class claz = classLoader.loadClass(className);
package www.it.com.reflect;
import javax.sound.midi.Soundbank;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.FormatFlagsConversionMismatchException;
/**
* @author wangjie
* @create 2019-09-21 11:35
* 反射的练习
*/
public class ReflectTest {
public static void main(String[] args) {
//创建user对象的class对象
Class<?> forName = null;
try {
forName = Class.forName("www.it.com.reflect.User");
//class对象通过调用user的无参构造方法创建user对象
User user =(User) forName.newInstance();
/**
* 方法名称 作用
* getDeclaredMethods [] 获取该类的所有方法
* getReturnType() 获取该类的返回值
* getParameterTypes() 获取传入参数
* getDeclaredFields() 获取该类的所有字段
* setAccessible 允许访问私有成员
*/
Method[] methods = forName.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
String typeName = forName.getTypeName();
Field[] fields = forName.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println(typeName);
user.setId("1");
System.out.println("使用反射机制获得use对象"+user.getId());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
import www.it.com.reflect.User;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Main {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
/* Class<User> userClass = User.class;
User user = userClass.newInstance();
user.setId("2");
user.setName("第二种获取反射类的方式");
System.out.println(user.toString()+"/t"+user.getName());*/
/**
* 通过有参构造获取获取反射的对象
*/
Class<User> userClass = User.class;
Constructor<User> constructor = userClass.getConstructor(String.class, String.class);
User user = constructor.newInstance("1", "2");
user.setName("使用有参构造方法获取user对象");
System.out.println(user.getName());
}
}
标签:dex 允许 illegal strong tcl declared 运行时 参数 common
原文地址:https://www.cnblogs.com/wang66a/p/12069291.html