具有动态字符串的Class.forName(String)不起作用

时间:2018-10-19 08:52:57

标签: java

此代码:

private BasePlayer addPlayer(Player player) {
    BasePlayer currentPlayer;
    try{
      String playerClassName = this.getClass().getPackage().toString() + ".Player";
      Class cPlayer = Class.forName(playerClassName);
      Constructor constructor = cPlayer.getConstructor(new Class[]{ Player.class });
      currentPlayer = (BasePlayer) constructor.newInstance(new Object[]{player});
    } catch (ClassNotFoundException e) {
      log.info(e.toString());
      currentPlayer = new BasePlayer(player);
    } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException e) {
      log.info(e.toString());
      return null;
    }
    log.info(player.getName() + " added to player list with UUID: " + player.getUniqueId().toString());
    playerMap.put(player.getUniqueId(), currentPlayer);
    return currentPlayer;
  }

引发异常

  

Java.lang.ClassNotFoundException:包com.warnea.codecraft.Player

但是如果我改变

      String playerClassName = this.getClass().getPackage().toString() + ".Player";
      Class cPlayer = Class.forName(playerClassName);

      String playerClassName = "com.warnea.codecraft.Player";
      Class cPlayer = Class.forName(playerClassName);

它工作正常。为什么我似乎需要对软件包名称进行硬编码?

0 个答案:

没有答案