1. Class 对象:
- 所有的类都是在对其第一次使用的时候,动态加载到JVM中的。当程序创建第一个对类的静态成员的引用时,就会加载这个类。这说明构造器也是类的静态方法。即使在构造器之前并没有static关键字,这个类也会被加载。
- java程序在它开始运行之前并非完全被加载。其各个部分是在必要时才加载的。
- 类加载器的执行过程
@H_403_9@
1、 类加载器首先检查这个类的Class对象是否已经加载。如果尚未加载,默认的类加载器就会根据类名查找.class文件。
2、在这个类的字节码被加载是,他们会接收验证,以确保其没有被损坏。并且不包含不良代码。这时java中用于安全防范目的的措施之一。
3、一旦某个类被加载,他就用来创建这个类的所有对象。
下面这个例子说明了一下两点:
1. 类何时被加载
2. 如何加载
package net.mindview.typeinfo;
/**
* 首先,下面的每一个类都有一个静态的代码块.
* 这个代码块, 在类第一次被加载时执行。
* @author samsung
*
*/
class Candy {
static {
System.out.println("Loading Candy!");
}
}
Gum {
Loading Gum! Cookie {
Loading Cookie!public SweetShop {
static void main(String[] args) {
System.inside main);
//第一次new的时候,就加载了类Candy. 以后都是从这个类中创建实例对象
new Candy();
System.After creating Candy!try {
Class.forName 获取对象引用的一种方法.参数是类的全限定文件名. 返回值是一个Class对象的引用.
如果Gum没有被加载,那么这个类就会被加载.
使用类加载器加载类Gum,在第一次加载Gum时,也会主动去加载Gum这个类,以后就从这个类中创建实例.
Class.forName(Gum);
} catch (ClassNotFoundException e) {
System.Could`t find Gum);
}
System.After Class.forName("Gum") Cookie();
System.After creating Cookie);
这个例子展示,第二次实例化Cookie是,static静态代码块没有被再次执行,它只会在第一次加载时执行.
After creating Cookie twice);
}
}
- 下面展示如何通过Class来发现整个类的基本结构. 详细看代码注释
package net.mindview.typeinfo.toys;
*
* 以下:展示了完全的获取一个类的完整的继承结构.
* @author samsung
*
*/
interface HasBatteries {}
Waterproof {}
Shoots {}
Toy{
Toy(){}
Toy(int i){}
}
FancyToy extends Toy implements HasBatteries,Waterproof,Shoots{
FancyToy() {super(1);}
}
ToyTest {
printInfo(Class cc){
*
* 这里调用了Class的一些基本方法
* cc.isInterface(): 是接口么
* cc.getSimpleName(): 类名,不含路径
* cc.getCanonicalName(): 全限定类名
*/
System.Class name:" + cc.getName() + is interface ? [" + cc.isInterface() + ]);
System.Simple name: " + cc.getSimpleName());
System.Canonical name: "+ cc.getCanonicalName());
}
main(String[] args) {
Class c = null;
这里必须使用全限定名
c = Class.forName(net.mindview.typeinfo.toys.FancyToyCan`t find FancyToy);
System.exit();
}
printInfo(c);
System.out.println();
*
* c.getInterfaces(): 获取这个类已继承的所有的接口
*/
for(Class face: c.getInterfaces()){
打印接口类
printInfo(face);
System..println();
}
*
* c.getSuperclass(): 获取这个类的父类
Class up = c.getSuperclass();
Object obj = 将父类实例化
使用newInstance来实例化的类不许带有一个默认的构造器
obj = up.newInstance();
} (InstantiationException e) {
System.Can`t instantiate (IllegalAccessException e) {
System.);
}
打印父类基本细腻
printInfo(obj.getClass());
}
}
运行结果:
Class name:net.mindview.typeinfo.toys.FancyToy is interface ? [false]
Simple name: FancyToy
Canonical name: net.mindview.typeinfo.toys.FancyToy
Class name:net.mindview.typeinfo.toys.HasBatteries true]
Simple name: HasBatteries
Canonical name: net.mindview.typeinfo.toys.HasBatteries
Class name:net.mindview.typeinfo.toys.Waterproof ]
Simple name: Waterproof
Canonical name: net.mindview.typeinfo.toys.Waterproof
Class name:net.mindview.typeinfo.toys.Shoots ]
Simple name: Shoots
Canonical name: net.mindview.typeinfo.toys.Shoots
Class name:net.mindview.typeinfo.toys.Toy ]
Simple name: Toy
Canonical name: net.mindview.typeinfo.toys.Toy
总结:??
package net.mindview.typeinfo;
WildcardClassReferences {
main(String[] args) {
*
* Class<?> 使用的时通配符来表示泛型.
Class<?> clazz = int.;
clazz = double.;
}
}
- 创建限定某种类型的Class, 可以使用?extends Number形式。
BoundedClassReferences {
main(String[] args) {
Class<? extends Number> clazz = 下面这句话就是报编译异常,因为String 不是Number的一类
clazz = String.class;
}
}
?
- 使用泛型类存储一个类。如下例:
package net.mindview.typeinfo;
import java.util.ArrayList;
import java.util.List;
*
* 定义一个IntegerCounted类--Integer计数器
CountedInteger {
计数器总数
private long counter;
每一个计数类的编号
private final long id = counter ++打印计数器编号
public String toString(){return Long.toString(id);};
}
class FilledList<T> {
这里定义一个类型,表示该类是处理拿一个特定类型的,在实例化的时候,传递实际类型
Class<T> type;
public FilledList(Class<T> type){
this.type = type;
}
public List<T> create( number) throws InstantiationException,IllegalAccessException{
List<T> list = new ArrayList<T>();
for(int i=0; i<number; i++){
list.add(type.newInstance());
}
list;
}
{
FilledList<CountedInteger> fl = new FilledList(CountedInteger.);
List<CountedInteger> list = fl.create(5);
打印list集合,就是调用list集合中每个元素的toString方法
System..println(list);
} (InstantiationException e) {
e.printStackTrace();
} (IllegalAccessException e) {
e.printStackTrace();
}
}
}
?
- 如果你知道某个具体类, 想获得这个具体类的超类, 使用“”?super 具体类“的方式实现,如下例:
Shoots {}
other {}
printInfo(obj.getClass());
}
}
?
GenericToyTest {
main(String[] args) throws InstantiationException,IllegalAccessException {
Class<FancyToy> ftClass = FancyToy.;
FancyToy fancyToy = ftClass.newInstance();
如果你想得到某个实现类的超类,那么他的Class应该如何写呢?
Class<? super FancyToy> up = ftClass.getSuperclass();
Class<Toy> up1 = ftClass.getSuperclass();
Object obj = up.newInstance();
}
*
* 这里FancyToy的超类是Toy. 而我想得到Toy这个超类,并不能直接这样写
* Class<Toy> up = ftClass.getSuperclass();
* 这样编译不通过.
}
?
- 使用instanceof判断类型. 最好在进行向下转型时,都是用instanceof进行判断
package net.mindview.typeinfo;
import net.mindview.initialization.Dog;
*
* 类型判断
InstanceofTest {
这里就是对x的类型进行的判断
if(x instanceof String){
执行String类型的方法
}
}
}
?
@H_403_9@
4. 反射
- getMethods()方法,获取的时整个继承树中的全部方法
- getConstructors()方法,获取的是所有的构造器?
- 可以通过解析对象所代表的方法,并获取其名字,返回值,参数等信息.
- 也可以使用toString()方法,返回的是包含有完整方法特征信息的字符串. 包括 返回值,返回类型,参数等.
package net.mindview.typeinfo;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
ShowMethods {
static String usage = ""
+ usage:n"
+ ShowMethods qualified.class.namenTo show all methods in class or:nShowMethods qualified.class.name. wordnTo search for methodds invoiving 'word';
static Pattern p = Pattern.compile(w+.);
if(args.length<){
System..println(usage);
System.exit();
}
int lines = 0;
{
Class<?> c = Class.forName(args[]);
getMethods获取的是整个继承树中所有的方法
Method[] methods = c.getMethods();
获取已有的构造器
Constructor[] ctors = c.getConstructors();
if(args.length == ){
打印所有继承树中的方法名
(Method method: methods){
System.out.println(p.matcher(method.toString()).replaceAll(""));
}
打印全部构造器
(Constructor ctor: ctors){
System.out.println(p.matcher(ctor.toString()).replaceAll());
}
lines = methods.length + ctors.length;
}else {
打印指定类中的方法
(Method method: methods){
if(method.toString().indexOf(args[1]) != -){
System.));
lines++;
}
}
打印构造器
(Constructor ctor :ctors){
if(ctor.toString().indexOf(args[1])!=-;
}
}
}
} (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
输入参数
net.mindview.typeinfo.ShowMethods
运行结果:
main(String[])
public final void wait(long,) throws InterruptedException
public final native wait() throws InterruptedException
public boolean equals(Object)
String toString()
public native hashCode()
final native Class getClass()
notify()
notifyAll()
public ShowMethods()
输入参数
net.mindview.typeinfo.ShowMethods
net.mindview.typeinfo.ShowMethods
运行结果
public ShowMethods()
?
@H_403_9@
? (编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|