获得反射对象
大约 2 分钟Java注解和反射
Java反射机制研究及应用
- 在运行时判断任意一个对象所属的类;
- 在运行时构造任意一个类的对象;
- 在运行时判断任意一个类所具有的成员变量和方法(通过反射甚至可以调用private方法);
- 在运行时调用任意一个对象的方法
- 工厂模式:Factory类中用反射的话,添加了一个新的类之后,就不需要再修改工厂类Factory了
- 数据库JDBC中通过Class.forName(Driver).来获得数据库连接驱动
- 分析类文件:毕竟能得到类中的方法等等
- 访问一些不能访问的变量或属性:破解别人代码
Java反射优点和缺点
优点:可以实现动态创建对象和编译,体现出很大的灵活性。
缺点:对性能有影响。使用反射基本上是一种解释操作,我们可以告诉JVM,我们希望做什么并且它满足我们的需求。这类操作总是慢于直接执行相同的操作。
反射相关的主要API
- java.lang.Class
- java.lang.reflect.Method
- java.lang.reflect.Field
- java.lang.reflect.Constructor
测试
/**
* @Description TODO
* @Author Administrator
* @Date 2020/11/28 18:50
*/
public class Test extends Object {
public static void main(String[] args) throws ClassNotFoundException {
/**
* 反射获取
*/
Class c1 = Class.forName("com.hejin.reflection.User");
System.out.println(c1);
Class c2 = Class.forName("com.hejin.reflection.User");
Class c3 = Class.forName("com.hejin.reflection.User");
Class c4 = Class.forName("com.hejin.reflection.User");
System.out.println(c1.hashCode());
System.out.println(c2.hashCode());
System.out.println(c3.hashCode());
System.out.println(c4.hashCode());
}
}
class User{
private int id;
private String name;
private int age;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
结果
class com.hejin.reflection.User
356573597
356573597
356573597
356573597
Process finished with exit code 0
Object有一个方法getClass,会返回Class对象。
/**
* Returns the runtime class of this {@code Object}. The returned
* {@code Class} object is the object that is locked by {@code
* static synchronized} methods of the represented class.
*
* <p><b>The actual result type is {@code Class<? extends |X|>}
* where {@code |X|} is the erasure of the static type of the
* expression on which {@code getClass} is called.</b> For
* example, no cast is required in this code fragment:</p>
*
* <p>
* {@code Number n = 0; }<br>
* {@code Class<? extends Number> c = n.getClass(); }
* </p>
*
* @return The {@code Class} object that represents the runtime
* class of this object.
* @jls 15.8.2 Class Literals
*/
public final native Class<?> getClass();
Class对象创建方式
Class.forName("完整路径类名")
Object.getClass()