Java Class 详解

       Java程序在运行时,Java运行时系统一直对所有的对象进行所谓的运行时类型标识。这项信息纪录了每个对象所属的类。虚拟机通常使用运行时类型信息选准正确方法去执行,用来保存这些类型信息的类是Class类。Class类封装一个对象和接口运行时的状态,当装载类时,Class类型的对象自动创建。
      Class 没有公共构造方法。Class 对象是在加载类时由 Java 虚拟机以及通过调用类加载器中的 defineClass 方法自动构造的,因此不能显式地声明一个Class对象。 
      虚拟机为每种类型管理一个独一无二的Class对象。也就是说,每个类(型)都有一个Class对象。运行程序时,Java虚拟机(JVM)首先检查是否所要加载的类对应的Class对象是否已经加载。如果没有加载,JVM就会根据类名查找.class文件,并将其Class对象载入。(可以想象,两个对象role1 和 role2如果都是类Role的实例,role1.getClass() 和 role2.getClass() 得到的对象是同一个Class对象的引用。
      基本的 Java 类型(boolean、byte、char、short、int、long、float 和 double)和关键字 void 也都对应一个 Class 对象。 
      每个数组属于被映射为 Class 对象的一个类,所有具有相同元素类型和维数的数组都共享该 Class 对象。

      一般某个类的Class对象被载入内存,它就用来创建这个类的所有对象。


一、如何得到Class的对象呢?有三种方法可以的获取
    1、调用Object类的getClass()方法来得到Class对象,这也是最常见的产生Class对象的方法。例如:
    MyObject x;

    Class c1 = x.getClass();

     2、使用Class类的中静态forName()方法获得与字符串对应的Class对象。例如: 
    Class c2=Class.forName("包名 + MyObject")。


    3、获取Class类型对象的第三个方法非常简单。如果T是一个Java类型,那么T.class就代表了匹配的类对象。例如
    Class cl1 = Manager.class;
    Class cl2 = int.class;
    Class cl3 = Double[].class;

二、常用方法及用法详解

package test.uitls;
import java.lang.reflect.Constructor;
import javax.persistence.Entity;
import org.hibernate.annotations.AccessType;
import org.springframework.transaction.annotation.Transactional;
import test.model.AbsEntity;
import test.model.Role;

public class ReflectionUtils {

	public static void main(String args[]) throws NoSuchMethodException, SecurityException,
	NoSuchFieldException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		System.out.println("getName() : " + Role.class.getName());//返回class或interface的包名+类名。
		System.out.println("getClassLoader() : " + Role.class.getClassLoader());
		
		System.out.println("getConstructors : " + Role.class.getConstructors());//返回这个类所有的public构造器
		System.out.println("getConstructor : " + Role.class.getConstructor());//返回含有某个特定参数类型的public修饰的构造器。
		Constructor[] Constructors = Role.class.getDeclaredConstructors();//返回这个类所有由 public, protected, default (package) access, private修饰的构造器。
		for (int i = 0; i < Constructors.length; i++) {
			System.out.println("getDeclaredConstructors " + (i + 1) + " : " + Constructors[i]);
		}
		System.out.println("getDeclaredConstructor : " + Role.class.getDeclaredConstructor(String.class));//返回某个含有特定参数类型的public, protected, default
	    //(package) access, private修饰的构造器。
		
		System.out.println("getFields : " + Role.class.getFields().length);//返回所有这个类所有Public修饰属性, 包括继承来的属性.
		System.out.println("getField : " + Role.class.getField("id"));//返回所有这个类特定名称public修饰的某个属性, 包括继承来的属性(返回Field类型)。
		System.out.println("getDeclaredFields : " + Role.class.getDeclaredFields().length);//返回这个类所有 public, protected, default
	    //(package) access, private修饰的属性, 但不包括继承来的属性。
		System.out.println("getDeclaredField : " + Role.class.getDeclaredField("roleName"));//返回这个类含有某个特定名称的,并包括由public, protected, default
	    //(package) access, private修饰的属性。
		
		System.out.println("getMethods : " + Role.class.getMethods().length);//返回所有这个类所有Public修饰属性, 包括继承来的方法.
		System.out.println("getMethod : " + Role.class.getMethod("getId"));//返回所有这个类特定名称public修饰的某个方法, 包括继承来的方法(返回Method类型)。
		System.out.println("getDeclaredMethods : " + Role.class.getDeclaredMethods().length);//返回这个类所有 public, protected, default
		//(package) access, private修饰的方法, 但不包括继承来的方法。
		System.out.println("getDeclaredMethod : " + Role.class.getDeclaredMethod("getRoleName"));//返回这个类含有某个特定名称的,并包括由public, protected, default
		//(package) access, private修饰的方法。
		
		System.out.println("getSuperclass : " + Role.class.getSuperclass());//返回父类的Class对象。一个对象只有一个superclass.
		System.out.println("getSuperclass : " + AbsEntity.class.getSuperclass());
//		System.out.println(IEntity.class.getSuperclass());//最上层的接口的超类居然不是object?
		
		System.out.println("getInterfaces : " + Role.class.getInterfaces()[0]);//返回这个类实现的接口。
		System.out.println("Role is Interface : " + Role.class.isInterface());//判断这个Class对象是否是一个接口。
		
		System.out.println("Role is Annotation : " + Role.class.isAnnotation());//判断这个Class对象是否是一个注释。
		System.out.println("Transactional is Annotation : " + Transactional.class.isAnnotation());
		System.out.println("get Role's Entity Annotation : " + Role.class.getAnnotation(Entity.class));//获取这个类的的注释Entity,Entity没有注释这个类返回null。
		System.out.println("get Role's AccessType Annotation : " + Role.class.getAnnotation(AccessType.class));
		System.out.println("get Role's Transactional Annotation  : " + Role.class.getAnnotation(Transactional.class));
		
		Role myrole = new Role();
		System.out.println("Role is Instance Of myrole : " + Role.class.isInstance(myrole));//是否是某个对象的实例。
		
		Class roleClass = Class.forName("test.model.Role");
		Role role = (Role)roleClass.newInstance();//这个类一定要有一个默认构造器或public无参构造器。
		role.getDisplayString();
	}
} 



三、结果
getName() : test.model.Role
getClassLoader() : sun.misc.Launcher$AppClassLoader@3feef1eb
getConstructors : [Ljava.lang.reflect.Constructor;@6411c21b
getConstructor : public test.model.Role()
getDeclaredConstructors 1 : public test.model.Role()
getDeclaredConstructors 2 : private test.model.Role(java.lang.String)
getDeclaredConstructor : private test.model.Role(java.lang.String)
getFields : 3
getField : public java.lang.String test.model.AbsEntity.id
getDeclaredFields : 2
getDeclaredField : public java.lang.String test.model.Role.roleName
getMethods : 16
getMethod : public java.lang.String test.model.AbsEntity.getId()
getDeclaredMethods : 5
getDeclaredMethod : public java.lang.String test.model.Role.getRoleName()
getSuperclass : class test.model.AbsEntity
getSuperclass : class java.lang.Object
getInterfaces : interface test.model.IEntity
Role is Interface : false
Role is Annotation : false
Transactional is Annotation : true
get Role's Entity Annotation : @javax.persistence.Entity(name=)
get Role's AccessType Annotation : null
get Role's Transactional Annotation  : null
Role is Instance Of myrole : true
I am a Role



四、用到的接口和类
package test.model;

public interface IEntity {
	public String getDisplayString();
}



package test.model;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.AccessType;
import org.hibernate.annotations.GenericGenerator;

public abstract class AbsEntity {
	
	@Id
	@GeneratedValue(generator = "system-uuid")
	@GenericGenerator(name = "system-uuid", strategy = "uuid.hex")
	@Column(length = 40)
	@AccessType("property")
	public String id;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
}



package test.model;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(schema = "public")
public class Role extends AbsEntity implements IEntity{
	public String roleName;
	
	public String userId;

	public Role() {}
	
	private Role(String roleName) {
		this.roleName = roleName;
	}
	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getDisplayString() {
		System.out.println("I am a Role");
		return "Role";
	}
	
}


五、不长用方法

1.isAssignableFrom(class<?> cls) 判断这个类是否是cls的父类或与cls相同的类。




转载于:https://my.oschina.net/u/1583086/blog/267776

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值