这里用到的是反射的机制!
这里你想要调用这个类有两种方式!
可以选择直接newInstace 实例化对象。如下:- Class<?> clazz = Class.forName(className); //首先加载驱动
- Object obj = clazz.newInstance(); //实例化对象
- Method method = clazz.getMethod(methodName); //根据方法名,获取Method对象,
- result = (String)method.invoke(obj); //调用方法
复制代码 也可以先获取构造方法,利用构造方法去实例化对象。如下:
- Constructor<?> ct = Class.forName("com.test.Person").getConstructor
- Person person = (Person)ct.newInstance();
复制代码 这里要注意的是开始只是获取构造器,但并没有去初始化它。只有在实例对象的时候,才会去调用构造器。
还有就是其实第一种方式也需要去调用构造方法。
如果不信的话可以去查下API 或者JDK 的源码。下面给一段JDK核心代码:- private T newInstance0()
- throws InstantiationException, IllegalAccessException
- {
- // NOTE: the following code may not be strictly correct under
- // the current Java memory model.
- // Constructor lookup
- if (cachedConstructor == null) {
- if (this == Class.class) {
- throw new IllegalAccessException(
- "Can not call newInstance() on the Class for java.lang.Class"
- );
- }
- try {
- Class[] empty = {};
- final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
- // Disable accessibility checks on the constructor
- // since we have to do the security check here anyway
- // (the stack depth is wrong for the Constructor's
- // security check to work)
- java.security.AccessController.doPrivileged
- (new java.security.PrivilegedAction() {
- public Object run() {
- c.setAccessible(true);
- return null;
- }
- });
- cachedConstructor = c;
- } catch (NoSuchMethodException e) {
- throw new InstantiationException(getName());
- }
- }
- Constructor<T> tmpConstructor = cachedConstructor;
- // Security check (same as in java.lang.reflect.Constructor)
- int modifiers = tmpConstructor.getModifiers();
- if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
- Class caller = Reflection.getCallerClass(3);
- if (newInstanceCallerCache != caller) {
- Reflection.ensureMemberAccess(caller, this, null, modifiers);
- newInstanceCallerCache = caller;
- }
- }
- // Run constructor
- try {
- return tmpConstructor.newInstance((Object[])null);
- } catch (InvocationTargetException e) {
- Unsafe.getUnsafe().throwException(e.getTargetException());
- // Not reached
- return null;
- }
- }
复制代码 这些也不用全部看懂!仔细看看就知道,它同样也要去获取构造器去实例化对象。 |