欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用反射获取父类,接口信息 博客分类: java基础 javareflect 

程序员文章站 2024-02-13 18:10:16
...
这个例子好似来自tij-4,(太久没更新博客了,不记得了)。
这个例子主要是用来说明,运行时能获取的被实现的接口,被继承的类的信息。
在实际开发中是一个蛮常用的手段,比如在框架中要检查某个类是否实现了某一接口。

package org.iteye.bbjava.runtimeinformation;




class Toy {

	/**
	 * It's a contructor of Toy class,it could be used contructing an object of
	 * Toy at runtime.
	 * */
	public Toy() {
		// TODO Auto-generated constructor stub
	}

	public Toy(int i) {

	}
}

interface HasBatteries {

}

interface Waterproof {

}

interface Shoots {

}

class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots {
	FancyToy() {
		super(1);
	}
}

public class ToyTest {
	static void printInfo(Class cc) {
		System.out.println("Class name: " + cc.getName() + " is interface?["
				+ cc.isInterface() + "]");
		System.out.println("Simple name: " + cc.getSimpleName());
		System.out.println("Canonical name: " + cc.getCanonicalName());
	}

	public static void main(String[] args) {
		Class c = null;
		try {
			c = Class.forName("org.iteye.bbjava.runtimeinformation.FancyToy");

		} catch (Exception e) {
			System.out.println("Can't find FancyToy");
			System.exit(1);
		}
		printInfo(c);

		for (Class face : c.getInterfaces()) {
			printInfo(face);
			Class up = c.getSuperclass();
			Object obj = null;
			try {
				obj = up.newInstance();

			} catch (InstantiationException e) {
				System.out.println("Can't getInstance from up object");
				System.exit(1);
			} catch (IllegalAccessException e) {
				System.out.println("Can't access");
				System.exit(1);
			}
			printInfo(obj.getClass());
		}
	}
}



console info:
引用
Class name: org.iteye.bbjava.runtimeinformation.FancyToy is interface?[false]
Simple name: FancyToy
Canonical name: org.iteye.bbjava.runtimeinformation.FancyToy
Class name: org.iteye.bbjava.runtimeinformation.HasBatteries is interface?[true]
Simple name: HasBatteries
Canonical name: org.iteye.bbjava.runtimeinformation.HasBatteries
Class name: org.iteye.bbjava.runtimeinformation.Toy is interface?[false]
Simple name: Toy
Canonical name: org.iteye.bbjava.runtimeinformation.Toy
Class name: org.iteye.bbjava.runtimeinformation.Waterproof is interface?[true]
Simple name: Waterproof
Canonical name: org.iteye.bbjava.runtimeinformation.Waterproof
Class name: org.iteye.bbjava.runtimeinformation.Toy is interface?[false]
Simple name: Toy
Canonical name: org.iteye.bbjava.runtimeinformation.Toy
Class name: org.iteye.bbjava.runtimeinformation.Shoots is interface?[true]
Simple name: Shoots
Canonical name: org.iteye.bbjava.runtimeinformation.Shoots
Class name: org.iteye.bbjava.runtimeinformation.Toy is interface?[false]
Simple name: Toy
Canonical name: org.iteye.bbjava.runtimeinformation.Toy
相关标签: java reflect