79 lines
2.2 KiB
Java
Raw Normal View History

// reflection/toys/ToyTest.java
// (c)2021 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.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Testing class Class
// {java reflection.toys.ToyTest}
package reflection.toys;
2020-10-07 17:06:42 -06:00
import java.lang.reflect.InvocationTargetException;
2015-06-15 17:47:35 -07:00
interface HasBatteries {}
interface Waterproof {}
interface Shoots {}
class Toy {
// Comment out the following zero-argument
2015-12-15 11:47:04 -08:00
// constructor to see NoSuchMethodError
public Toy() {}
public Toy(int i) {}
2015-06-15 17:47:35 -07:00
}
class FancyToy extends Toy
implements HasBatteries, Waterproof, Shoots {
public FancyToy() { super(1); }
2015-06-15 17:47:35 -07:00
}
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
}
2020-10-07 17:06:42 -06:00
@SuppressWarnings("deprecation")
2015-06-15 17:47:35 -07:00
public static void main(String[] args) {
Class c = null;
try {
c = Class.forName("reflection.toys.FancyToy");
2015-06-15 17:47:35 -07:00
} 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 {
// Requires public zero-argument constructor:
2015-06-15 17:47:35 -07:00
obj = up.newInstance();
2020-10-07 17:06:42 -06:00
} catch(Exception e) {
throw new
RuntimeException("Cannot instantiate");
2015-06-15 17:47:35 -07:00
}
printInfo(obj.getClass());
}
2015-09-07 11:44:36 -06:00
}
/* Output:
Class name: reflection.toys.FancyToy is interface?
[false]
2015-06-15 17:47:35 -07:00
Simple name: FancyToy
Canonical name : reflection.toys.FancyToy
Class name: reflection.toys.HasBatteries is interface?
[true]
2015-06-15 17:47:35 -07:00
Simple name: HasBatteries
Canonical name : reflection.toys.HasBatteries
Class name: reflection.toys.Waterproof is interface?
[true]
2015-06-15 17:47:35 -07:00
Simple name: Waterproof
Canonical name : reflection.toys.Waterproof
Class name: reflection.toys.Shoots is interface? [true]
2015-06-15 17:47:35 -07:00
Simple name: Shoots
Canonical name : reflection.toys.Shoots
Class name: reflection.toys.Toy is interface? [false]
2015-06-15 17:47:35 -07:00
Simple name: Toy
Canonical name : reflection.toys.Toy
2015-09-07 11:44:36 -06:00
*/