76 lines
2.1 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// typeinfo/toys/ToyTest.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Testing class Class
2015-06-15 17:47:35 -07:00
package typeinfo.toys;
interface HasBatteries {}
interface Waterproof {}
interface Shoots {}
class Toy {
2015-12-15 11:47:04 -08:00
// Comment out the following no-arg
// constructor to see NoSuchMethodError
2015-06-15 17:47:35 -07:00
Toy() {}
Toy(int i) {}
}
class FancyToy extends Toy
implements HasBatteries, Waterproof, Shoots {
FancyToy() { super(1); }
}
public class ToyTest {
static void printInfo(Class cc) {
2015-11-03 12:00:44 -08:00
System.out.println("Class name: " + cc.getName() +
2015-06-15 17:47:35 -07:00
" is interface? [" + cc.isInterface() + "]");
2015-12-02 09:20:27 -08:00
System.out.println(
"Simple name: " + cc.getSimpleName());
System.out.println(
"Canonical name : " + cc.getCanonicalName());
2015-06-15 17:47:35 -07:00
}
public static void main(String[] args) {
Class c = null;
try {
c = Class.forName("typeinfo.toys.FancyToy");
} catch(ClassNotFoundException e) {
2015-11-03 12:00:44 -08:00
System.out.println("Can't find FancyToy");
2015-06-15 17:47:35 -07:00
System.exit(1);
}
printInfo(c);
for(Class face : c.getInterfaces())
printInfo(face);
Class up = c.getSuperclass();
Object obj = null;
try {
2015-11-03 12:00:44 -08:00
// Requires no-arg constructor:
2015-06-15 17:47:35 -07:00
obj = up.newInstance();
} catch(InstantiationException e) {
2015-11-03 12:00:44 -08:00
System.out.println("Cannot instantiate");
2015-06-15 17:47:35 -07:00
System.exit(1);
} catch(IllegalAccessException e) {
2015-11-03 12:00:44 -08:00
System.out.println("Cannot access");
2015-06-15 17:47:35 -07:00
System.exit(1);
}
printInfo(obj.getClass());
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Class name: typeinfo.toys.FancyToy is interface? [false]
Simple name: FancyToy
Canonical name : typeinfo.toys.FancyToy
Class name: typeinfo.toys.HasBatteries is interface? [true]
Simple name: HasBatteries
Canonical name : typeinfo.toys.HasBatteries
Class name: typeinfo.toys.Waterproof is interface? [true]
Simple name: Waterproof
Canonical name : typeinfo.toys.Waterproof
Class name: typeinfo.toys.Shoots is interface? [true]
Simple name: Shoots
Canonical name : typeinfo.toys.Shoots
Class name: typeinfo.toys.Toy is interface? [false]
Simple name: Toy
Canonical name : typeinfo.toys.Toy
2015-09-07 11:44:36 -06:00
*/