abstract class Shape {
// this 调用当前类的toString()方法,返回实际的内容
void draw(){ System.out.println(this + "draw()"); }
// 声明 toString()为abstract类型,强制集成在重写该方法
abstract public String toString();
}
class Circle extends Shape {
public String toString(){ return "Circle"; }
}
class Square extends Shape {
public String toString(){ return "Square"; }
}
class Triangle extends Shape {
public String toString(){ return "Triangle"; }
}
public static void main(String[] args){
// 把Shape对象放入List<Shape>的数组的时候会向上转型为Shape,从而丢失了具体的类型信息
List<Shape> shapeList = Arrays.asList(new Circle(), new Square(), new Triangle());
// 从数组中取出时,这种容器,实际上所有的元素都当成Object持有,会自动将结果转型为Shape,这就是RTTI的基本的使用。
for(Shape shape : shapeList){
shape.draw();
}
}
Circledraw() Squaredraw() Triangledraw()
class A {
// 静态代码库,在第一次被加载时执行,通过打印信息知道该类什么时候被加载
static { System.out.println("Loading A"); }
}
class B {
static { System.out.println("Loading B"); }
}
class C {
static { System.out.println("Loading C"); }
}
public class Load {
public static void main(String[] args){
System.out.println("execute main...");
new A();
System.out.println("after new A");
try {
Class.forName("com.itzhai.test.type.B");
} catch (ClassNotFoundException e) {
System.out.println("cloud not find class B");
}
System.out.println("after Class.forName B");
new C();
System.out.println("after new C");
}
}
execute main... Loading A after new A Loading B after Class.forName B Loading C after new C
interface X{}
interface Y{}
interface Z{}
class Letter {
Letter(){};
Letter(int i){};
}
class NewLetter extends Letter implements X, Y, Z{
NewLetter(){ super(1); };
}
public class ClassTest {
/**
* 打印类型信息
* @param c
*/
static void printInfo(Class c){
// getName()获得全限定的类名
System.out.println("Class name: " + c.getName() + " is interface? " + c.isInterface());
// 获得不包含包名的类名
System.out.println("Simple name: " + c.getSimpleName());
// 获得全限定类名
System.out.println("Canonical name: " + c.getCanonicalName());
}
public static void main(String[] args){
Class c = null;
try {
// 获得Class引用
c = Class.forName("com.itzhai.test.type.NewLetter");
} catch (ClassNotFoundException e) {
System.out.println("Can not find com.itzhai.test.type.NewLetter");
System.exit(1);
}
// 打印接口类型信息
for(Class face : c.getInterfaces()){
printInfo(face);
}
// 获取超类Class引用
Class up = c.getSuperclass();
Object obj = null;
try {
// 通过newInstance()方法创建Class的实例
obj = up.newInstance();
} catch (InstantiationException e) {
System.out.println("Can not instantiate");
} catch (IllegalAccessException e) {
System.out.println("Can not access");
}
// 打印超类类型信息
printInfo(obj.getClass());
}
}
Class name: com.itzhai.test.type.X is interface? true Simple name: X Canonical name: com.itzhai.test.type.X Class name: com.itzhai.test.type.Y is interface? true Simple name: Y Canonical name: com.itzhai.test.type.Y Class name: com.itzhai.test.type.Z is interface? true Simple name: Z Canonical name: com.itzhai.test.type.Z Class name: com.itzhai.test.type.Letter is interface? false Simple name: Letter Canonical name: com.itzhai.test.type.Letter
NewLetter.class;
class Data1{
static final int a = 1;
static final double b = Math.random();
static {
System.out.println("init Data1...");
}
}
class Data2{
static int a = 12;
static {
System.out.println("init Data2...");
}
}
class Data3{
static int a = 23;
static {
System.out.println("init Data3...");
}
}
public class ClassTest2 {
public static void main(String[] args){
System.out.println("Data1.class: ");
Class data1 = Data1.class;
System.out.println(Data1.a); // 没有初始化Data1
System.out.println(Data1.b); // 初始化了Data1
System.out.println(Data2.a); // 初始化了Data2
try {
Class data3 = Class.forName("com.itzhai.test.type.Data3"); // 初始化了Data3
} catch (ClassNotFoundException e) {
System.out.println("can not found com.itzhai.test.type.Data3...");
}
System.out.println(Data3.a);
}
}
Data1.class: 1 init Data1... 0.26771085109184534 init Data2... 12 init Data3... 23
static final double b = Math.random();
Class intCls = int.class; // 使用泛型限定Class指向的引用 Class<Integer> genIntCls = int.class; // 没有使用泛型的Clas可以重新赋值为指向任何其他的Class对象 intCls = double.class; // 下面的编译会出错 // genIntCls = double.class;
Class<?> intCls = int.class; intCls = String.class;
Class<? extends Number> num = int.class; // num的引用范围为Number及其子类,所以可以按照如下赋值 num = double.class; num = Number.class;
Dog dog = dogCls.newInstance();
abstract class Animal {
}
class Dog extends Animal{
}
// 下面的写法是错误的,只能返回 Class<? super Dog>类型
// Class<Animal> animalCls = dogCls.getSuperclass();
Class<? super Dog> animalCls = dogCls.getSuperclass();
// 通过获取的超类引用,只能创建返回Object类型的对象
Object obj = animalCls.newInstance();
Animal animal = new Dog(); Class<Dog> dogCls = Dog.class; Dog dog = dogCls.cast(animal); // 或者直接使用下面的转型方法 dog = (Dog)animal;
if(x instanceof Dog) ((Dog) x).bark();
public interface Attribute {
}
/**
* 创建一个抽象类
*/
public abstract class Shape{
// this调用了当前类的toString方法获得信息
public void draw() { System.out.println(this + ".draw()"); }
// 声明toString()方法为abstract,从而强制继承者需要重写该方法。
abstract public String toString();
}
public class Circle extends Shape implements Attribute{
public String toString(){ return "Circle"; }
}
public class Square extends Shape{
public String toString(){ return "Square"; }
}
public class Triangle extends Shape{
public String toString(){ return "Triangle"; }
}
// instanceOf
Circle c = new Circle();
// 判断是否超类的实例
System.out.format("Using instanceof: %s is a shape? %b\n",
c.toString(), c instanceof Shape);
// 判断是否Circle的实例
System.out.format("Using instanceof: %s is a circle? %b\n",
c.toString(), c instanceof Circle);
// 判断是否超类的实例
System.out.format("Using Class.isInstance: %s is a shape? %b\n",
c.toString(), Shape.class.isInstance(c));
// 判断是否接口的实例
System.out.format("Using Class.isInstance: %s is a Attribute? %b\n",
c.toString(), Attribute.class.isInstance(c));
public abstract class ShapeCreator {
private Random rand = new Random(10);
// 返回一个对象类型数组,由实现类提供,后面会看到两种实现形式,基于forName的和基于类字面常量的.class
public abstract List<Class<? extends Shape>> types();
// 随机生成一个对象类型数组中的类型对象实例
public Shape randomShape(){
int n = rand.nextInt(types().size());
try {
return types().get(n).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
// 生成一个随机数组
public Shape[] createArray(int size){
Shape[] result = new Shape[size];
for(int i=0; i<size; i++){
result[i] = randomShape();
}
return result;
}
// 生成一个随机数组,泛型的ArrayList
public ArrayList<Shape> arrayList(int size){
ArrayList<Shape> result = new ArrayList<Shape>();
Collections.addAll(result, createArray(size));
return result;
}
}
/**
* forName的生成器实现
* @author arthinking
*
*/
public class ForNameCreator extends ShapeCreator{
private static List<Class<? extends Shape>> types =
new ArrayList<Class<? extends Shape>>();
private static String[] typeNames = {
"com.itzhai.javanote.entity.Circle",
"com.itzhai.javanote.entity.Square",
"com.itzhai.javanote.entity.Triangle"
};
@SuppressWarnings("unused")
private static void loader(){
for(String name : typeNames){
try {
types.add((Class<? extends Shape>)Class.forName(name));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
// 初始化加载所需的类型数组
static {
loader();
}
public List<Class<? extends Shape>> types() {
return types;
}
}
public class ShapeCount {
static class ShapeCounter extends HashMap<String, Integer>{
public void count(String type){
Integer quantity = get(type);
if(quantity == null){
put(type, 1);
} else {
put(type, quantity + 1);
}
}
}
// 演示通过instanceof关键字统计对象类型
public static void countShapes(ShapeCreator creator){
ShapeCounter counter = new ShapeCounter();
for(Shape shape : creator.createArray(20)){
if(shape instanceof Circle)
counter.count("Circle");
if(shape instanceof Square)
counter.count("Square");
if(shape instanceof Triangle){
counter.count("Triangle");
}
}
System.out.println(counter);
}
public static void main(String[] args){
countShapes(new ForNameCreator());
}
}
/**
* 字面量的生成器实现
*/
public class LiteralCreator extends ShapeCreator{
public static final List<Class<? extends Shape>> allType =
Collections.unmodifiableList(Arrays.asList(Circle.class, Triangle.class, Square.class));
public List<Class<? extends Shape>> types(){
return allType;
}
public static void main(String[] args){
System.out.println(allType);
}
}
/**
* 通过使用Class.instanceof动态的测试对象,移除掉原来的ShapeCount中单调的instanceof语句
*
*/
public class ShapeCount2 {
private static final List<Class<? extends Shape>> shapeTypes = LiteralCreator.allType;
static class ShapeCounter extends HashMap<String, Integer>{
public void count(String type){
Integer quantity = get(type);
if(quantity == null){
put(type, 1);
} else {
put(type, quantity + 1);
}
}
}
// 演示通过Class.isInstance()统计对象类型
public static void countShapes(ShapeCreator creator){
ShapeCounter counter = new ShapeCounter();
for(Shape shape : creator.createArray(20)){
for(Class<? extends Shape> cls : shapeTypes){
if(cls.isInstance(shape)){
counter.count(cls.getSimpleName());
}
}
}
System.out.println(counter);
}
public static void main(String[] args){
countShapes(new ForNameCreator());
}
}
/**
* 现在生成器有了两种实现,我们在这里添加一层外观,设置默认的实现方式
*/
public class Shapes {
public static final ShapeCreator creator =
new LiteralCreator();
public static Shape randomShape(){
return creator.randomShape();
}
public static Shape[] createArray(int size){
return creator.createArray(size);
}
public static ArrayList<Shape> arrayList(int size){
return creator.arrayList(size);
}
}
System.out.println(new Circle() instanceof Circle); // true System.out.println(Shape.class.isInstance(new Circle())); // true System.out.println((new Circle()).getClass() == Circle.class); // true System.out.println((new Circle().getClass()).equals(Shape.class)); // false
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有