Java Class.forName Examples

Java Class.forName - 30 examples found. These are the top rated real world Java examples of Class.forName extracted from open source projects. You can rate examples to help us improve the quality of examples.
  /** Creates a service and its associated manager based on fully qualified class names. */
  private Service setupService(String serviceName, String managerName, HashSet<Object> managerSet)
      throws Exception {
    // get the service class and instance
    Class<?> serviceClass = Class.forName(serviceName);
    Service service = createService(serviceClass);

    // resolve the class and the constructor, checking for constructors
    // by type since they likely take a super-type of Service
    Class<?> managerClass = Class.forName(managerName);
    Constructor<?>[] constructors = managerClass.getConstructors();
    Constructor<?> managerConstructor = null;
    for (int i = 0; i < constructors.length; i++) {
      Class<?>[] types = constructors[i].getParameterTypes();
      if (types.length == 1) {
        if (types[0].isAssignableFrom(serviceClass)) {
          managerConstructor = constructors[i];
          break;
        }
      }
    }

    // if we didn't find a matching manager constructor, it's an error
    if (managerConstructor == null)
      throw new NoSuchMethodException(
          "Could not find a constructor " + "that accepted the Service");

    // create the manager and put it in the collection
    managerSet.add(managerConstructor.newInstance(service));

    return service;
  }
Example #2
0
  public String objectToXml(Object object) {
    String rtnStr = "";
    try {

      JAXBContext jaxbContext = cachedJaxb.get(pkgName);
      if (jaxbContext == null) {
        jaxbContext = JAXBContext.newInstance(pkgName);
        cachedJaxb.put(pkgName, jaxbContext);
      }

      Marshaller marshaller = jaxbContext.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_ENCODING, BcConstants.ENCODING);
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);

      Class docClazz = Class.forName(pkgName + ".Document");
      Class ofClazz = Class.forName(pkgName + ".ObjectFactory");
      Object factory = ofClazz.newInstance();
      Method method = ofClazz.getDeclaredMethod("createDocument", docClazz);
      JAXBElement jaxbElement = (JAXBElement) method.invoke(factory, docClazz.cast(object));

      StringWriter sw = new StringWriter();
      marshaller.marshal(jaxbElement, sw);
      rtnStr = sw.toString();

      // TODO remove the header in a better way: <?xml version="1.0" encoding="UTF-8"
      // standalone="yes"?>
      rtnStr = StringUtils.substringAfter(rtnStr, "?>").trim();
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
    return rtnStr;
  }
 private static Class<?> getClassObject(Object o) throws ClassNotFoundException {
   if (o == null) {
     System.out.println("null");
   }
   // 基本データ型の場合
   if (o instanceof Boolean) {
     return boolean.class;
   } else if (o instanceof Integer) {
     return int.class;
   } else if (o instanceof Double) {
     return double.class;
   } else if (o instanceof Long) {
     return long.class;
   } else if (o instanceof Short) {
     return short.class;
   } else if (o instanceof Character) {
     return char.class;
   } else if (o instanceof Byte) {
     return byte.class;
   } else if (o instanceof Float) {
     return float.class;
   }
   // 基本データ型以外の場合:forName()でクラスオブジェクトを取得
   else {
     System.out.println(Class.forName(strip(o.getClass().toString(), "class ")));
     return Class.forName(strip(o.getClass().toString(), "class "));
   }
 }
  /** Creates an instance of the factory. */
  public static ServiceFactory newInstance() throws ServiceException {
    String className = getFactoryClassName();

    Class cl = null;

    try {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      if (loader != null) cl = Class.forName(className, false, loader);
    } catch (NoSuchMethodError e) {
    } catch (ClassNotFoundException e) {
      throw new ServiceException(e);
    }

    if (cl == null) {
      try {
        cl = Class.forName(className);
      } catch (ClassNotFoundException e) {
        throw new ServiceException(e);
      }
    }

    try {
      return (ServiceFactory) cl.newInstance();
    } catch (IllegalAccessException e) {
      throw new ServiceException(e);
    } catch (InstantiationException e) {
      throw new ServiceException(e);
    }
  }
Example #5
0
  public void connect() {

    try {

      Class.forName("org.postgresql.Driver"); // ドライバクラスをロード
      // JDBCドライバの登録
      String driver = "org.postgresql.Driver";
      // データベースの指定
      String server = "localhost"; // PostgreSQL サーバ ( IP または ホスト名 )
      String defaultdbname = "postgres"; // デフォルトで存在するデータベース名
      String defaulturl = "jdbc:postgresql://" + server + "/" + defaultdbname;

      // String databaseName = "testdb"; // 今後データの書き込みに使用するデータベース名
      // String databaseurl = "jdbc:postgresql://" + server + "/" +
      // databaseName;

      String user = "postgres"; // データベース作成ユーザ名
      String password = ""; // データベース作成ユーザパスワード
      Class.forName(driver);

      // データベースとの接続
      con = DriverManager.getConnection(defaulturl, user, password);
      // データベースへ接続
      stmt = con.createStatement();
    } catch (Exception e) {

      e.printStackTrace();
    }
  }
  public Result check(Descriptor descriptor) {
    this.descriptor = descriptor;
    result = getInitializedResult();
    compName = getVerifierContext().getComponentNameConstructor();
    ClassLoader cl = getVerifierContext().getClassLoader();
    List<InjectionCapable> injectables = getInjectables(getClassName());
    for (InjectionCapable injectionCapable : injectables) {
      Set<InjectionTarget> iTargets = injectionCapable.getInjectionTargets();
      for (InjectionTarget target : iTargets) {
        try {
          if (target.isFieldInjectable()) {
            Class classObj = Class.forName(getClassName(), false, cl);
            Field field = classObj.getDeclaredField(target.getFieldName());
            testMethodModifiers(field.getModifiers(), "field", field);
          }
          if (target.isMethodInjectable()) {
            Class classObj = Class.forName(getClassName(), false, cl);
            Method method = getInjectedMethod(classObj, target.getMethodName());
            if (method == null) continue;
            testMethodModifiers(method.getModifiers(), "method", method);
          }
        } catch (Exception e) {
        } // ignore as it will be caught in other tests
      }
    }

    if (result.getStatus() != Result.FAILED) {
      addGoodDetails(result, compName);
      result.passed(
          smh.getLocalString(getClass().getName() + ".passed", "Valid injection method(s)."));
    }
    return result;
  }