Example usage for java.lang Class getDeclaredMethod

List of usage examples for java.lang Class getDeclaredMethod

Introduction

In this page you can find the example usage for java.lang Class getDeclaredMethod.

Prototype

@CallerSensitive
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

Usage

From source file:com.hybris.oms.rest.resources.TmallMQ2TestEnvResource.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@POST/*  w  w w .  j  a va 2  s.com*/
@Path("/receivemq")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
// public Response receiveMQfromProductEnv(@RequestBody Map<SourceType, Map<EventType, Queue<OrderCommand>>>
// commands){
public String receiveMQfromProductEnv(final String json) {
    try {
        logger.debug("Receive json is " + json.toString());

        final ObjectMapper om = new ObjectMapper();
        // List readValue = om.readValue(json, List.class);
        final Map raw = om.readValue(json, new TypeReference<HashMap<String, Object>>() {
        });

        // String topic = "";
        Message message = null;

        // Map messageMap = null;
        // Map<String, Map> rawMap = null;
        // Map contentMap = null;

        final Class c = Class.forName("com.taobao.api.internal.tmc.Message");
        final Method methodSetRaw = c.getDeclaredMethod("setRaw", Map.class);
        methodSetRaw.setAccessible(true);
        final Object tmallMessageObj = c.newInstance();
        // rawMap = new HashMap<String, Map>();
        // contentMap = (Map) messageMap.get("raw");
        // rawMap.put("content", (Map) contentMap.get("content"));
        raw.put("time", new Date(Long.valueOf(nullToZero(String.valueOf(raw.get("time"))))));
        methodSetRaw.invoke(tmallMessageObj, raw);

        message = (Message) tmallMessageObj;

        message.setContent(String.valueOf(raw.get("content")));
        message.setTopic(String.valueOf(raw.get("topic")));
        message.setId(Long.valueOf(String.valueOf(raw.get("id"))));
        message.setPubAppKey(String.valueOf(raw.get("publisher")));
        message.setOutgoingTime(new Date(Long.valueOf(nullToZero(String.valueOf(raw.get("outtime"))))));
        message.setUserId(Long.valueOf(nullToZero(String.valueOf(raw.get("userid")))));
        message.setUserNick(String.valueOf(raw.get("nick")));
        message.setContent(String.valueOf(raw.get("content")));

        // topic = message.getTopic();

        logger.debug("outgoing time is " + message.getOutgoingTime());
        logger.debug("time in raw is " + message.getRaw().get("time"));
        // for test only
        // final OrderCommand createOrderCommand = new CreateTmallOrderCommand(omsOrderRetrieverService, message);
        // OrderCommandsStorage.getInstance().addOrderCommand(SourceType.TMALL, EventType.ORDERCREATE,
        // createOrderCommand);

        // Add to singleton commands
        final OrderCommand command = OrderCommandFactory.createTmallOrderCommand(omsOrderRetrieverService,
                message, InnerSource.OTC);
        OrderCommandsStorage.getInstance().addOrderCommand(command.getChannelSource(), command.getEventType(),
                command);
        // if ("taobao_trade_TradeBuyerPay".equalsIgnoreCase(topic))
        // {
        // final OrderCommand createOrderCommand = new CreateTmallOrderCommand(omsOrderRetrieverService, message);
        // OrderCommandsStorage.getInstance().addOrderCommand(SourceType.TMALL, EventType.ORDERCREATE,
        // createOrderCommand);
        // }
        // else if ("taobao_refund_RefundCreated".equalsIgnoreCase(topic))
        // {
        // final OrderCommand createRefundcommand = new CreateTmallRefundCommand(omsOrderRetrieverService, message);
        // OrderCommandsStorage.getInstance().addOrderCommand(SourceType.TMALL, EventType.REFUNDCREATE,
        // createRefundcommand);
        // }
        // else if ("taobao_refund_RefundSuccess".equalsIgnoreCase(topic))
        // {
        // final OrderCommand refundSuccessCommand = new TmallRefundSuccessCommand(omsOrderRetrieverService, message);
        // OrderCommandsStorage.getInstance().addOrderCommand(SourceType.TMALL, EventType.REFUNDSUCCESS,
        // refundSuccessCommand);
        // }
        // else if ("taobao_refund_RefundClosed".equalsIgnoreCase(topic))
        // {
        // final OrderCommand refundCloseCommand = new TmallRefundCloseCommand(omsOrderRetrieverService, message);
        // OrderCommandsStorage.getInstance().addOrderCommand(SourceType.TMALL, EventType.REFUNDCLOSE,
        // refundCloseCommand);
        // }
        // else if ("taobao_trade_TradeSellerShip".equalsIgnoreCase(topic))
        // {
        // final OrderCommand createSellerShipcommand = new CreateTmallSellerShippingCommand(omsOrderRetrieverService,
        // message);
        // OrderCommandsStorage.getInstance().addOrderCommand(SourceType.TMALL, EventType.SELLERSHIP,
        // createSellerShipcommand);
        // }

    } catch (final Exception e) {
        logger.error("Failed to recieve Tmall message from Product Env. ", e);
    }
    return String.valueOf(OrderCommandsStorage.getInstance().getAllCommands().size());
}

From source file:net.unicon.academus.apps.ConfigHelper.java

public static Method getParser(Element e, Class defaultClass) {

    // Assertions.
    if (e == null) {
        String msg = "Argument 'e [Element]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }//w  w  w .  j a  v a 2  s  .  c o  m
    if (defaultClass == null) {
        String msg = "Argument 'defaultClass' cannot be null.";
        throw new IllegalArgumentException(msg);
    }

    Class implClass = defaultClass; // duh...
    Attribute impl = e.attribute("impl");
    if (impl != null) {
        String implementationClassName = "unknown class";
        try {
            implementationClassName = impl.getValue();

            // exception for backwards compatibility of SsoEntry impl declaration
            // in configuration files.
            String ssoEntryClassName = SsoEntry.class.getName();
            String ssoEntrySimpleClassName = SsoEntrySimple.class.getName();
            if (ssoEntryClassName.equals(implementationClassName)) {
                LOG.warn("impl=\"" + ssoEntryClassName + "\" appeared in Gateway configuration.  "
                        + "This declaration is deprecated and instead should be impl=\""
                        + ssoEntrySimpleClassName + "\"");
                implementationClassName = ssoEntrySimpleClassName;
            }

            implClass = Class.forName(implementationClassName);
        } catch (Throwable t) {
            String msg = "Unable to create a parser for the specified implementation:  " + impl.getValue();
            throw new RuntimeException(msg, t);
        }
    }

    Method rslt = null;
    try {
        rslt = implClass.getDeclaredMethod("parse", new Class[] { Element.class });
    } catch (Throwable t) {
        String msg = "Unable to create a parser for the specified implementation:  " + implClass.getName();
        throw new RuntimeException(msg, t);
    }

    return rslt;

}

From source file:org.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void doubleEnumAtRootCreatesIntBackedEnum() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/doubleEnumAsRoot.json",
            "com.example");

    Class<Enum> rootEnumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.enums.DoubleEnumAsRoot");

    assertThat(rootEnumClass.isEnum(), is(true));
    assertThat(rootEnumClass.getDeclaredMethod("fromValue", Double.class), is(notNullValue()));
    assertThat(isPublic(rootEnumClass.getModifiers()), is(true));
}

From source file:org.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void intEnumAtRootCreatesIntBackedEnum() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/integerEnumAsRoot.json",
            "com.example");

    Class<Enum> rootEnumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.enums.IntegerEnumAsRoot");

    assertThat(rootEnumClass.isEnum(), is(true));
    assertThat(rootEnumClass.getDeclaredMethod("fromValue", Integer.class), is(notNullValue()));
    assertThat(isPublic(rootEnumClass.getModifiers()), is(true));
}

From source file:com.greatmancode.craftconomy3.utils.OldFormatConverter.java

public void step2() throws SQLException, IOException, ParseException {
    Common.getInstance().sendConsoleMessage(Level.INFO,
            "Converting step 2: Inserting the data back in all the new tables");
    Common.getInstance().sendConsoleMessage(Level.INFO, "Creating the new tables");
    String dbType = Common.getInstance().getMainConfig().getString("System.Database.Type");

    if (dbType.equals("sqlite")) {
        Common.getInstance().sendConsoleMessage(Level.INFO,
                "You are using SQLite! This is now deprecated. Selecting H2 instead.");
        Common.getInstance().getMainConfig().setValue("System.Database.Type", "h2");
        dbType = "h2";
    }/* w w  w  . j  a va2s  . co m*/
    StorageEngine engine = null;
    HikariConfig config = new HikariConfig();
    if (dbType.equalsIgnoreCase("mysql")) {
        engine = new MySQLEngine();

    } else if (dbType.equalsIgnoreCase("h2")) {
        engine = new H2Engine();
    } else {
        throw new UnsupportedOperationException("Unknown database!");
    }
    Common.getInstance().sendConsoleMessage(Level.INFO, "Loading backup json file");
    File accountFile = new File(Common.getInstance().getServerCaller().getDataFolder(), "accounts.json");

    System.out.println(accountFile.exists());
    JSONObject jsonObject = (JSONObject) new JSONParser().parse(new FileReader(accountFile));
    Map<Integer, String> currenciesMap = new HashMap<>();

    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving currencies");
    //Create the currency table
    JSONArray currencyArray = (JSONArray) jsonObject.get("currencies");
    Iterator<JSONObject> iterator = currencyArray.iterator();
    while (iterator.hasNext()) {
        JSONObject obj = iterator.next();
        currenciesMap.put(((Long) obj.get("id")).intValue(), (String) obj.get("name"));
        Currency currency = new Currency((String) obj.get("name"), (String) obj.get("plural"),
                (String) obj.get("minor"), (String) obj.get("minorPlural"), (String) obj.get("sign"));
        try {
            Class clazz = currency.getClass();
            Method setDefault = clazz.getDeclaredMethod("setDefault", boolean.class);
            setDefault.setAccessible(true);
            setDefault.invoke(currency, (boolean) obj.get("status"));
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        engine.saveCurrency("", currency);
    }

    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving world groups...");
    JSONArray worldgroup = (JSONArray) jsonObject.get("worldgroups");
    iterator = worldgroup.iterator();
    while (iterator.hasNext()) {
        JSONObject obj = iterator.next();
        engine.saveWorldGroup((String) obj.get("groupName"), (String) obj.get("worldList"));
    }

    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving Exchange rates");
    JSONArray exchangeArray = (JSONArray) jsonObject.get("exchanges");
    iterator = exchangeArray.iterator();
    while (iterator.hasNext()) {
        JSONObject obj = iterator.next();
        int id_from = ((Long) obj.get("from_currency_id")).intValue();
        int id_to = ((Long) obj.get("to_currency_id")).intValue();
        engine.setExchangeRate(engine.getCurrency(currenciesMap.get(id_from)),
                engine.getCurrency(currenciesMap.get(id_to)), (double) obj.get("amount"));
    }

    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving configs");
    JSONArray configArray = (JSONArray) jsonObject.get("configs");
    iterator = configArray.iterator();
    while (iterator.hasNext()) {
        JSONObject obj = iterator.next();
        if (!obj.get("name").equals("dbVersion")) {
            engine.setConfigEntry((String) obj.get("name"), (String) obj.get("value"));
        }
    }

    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving accounts. This may take a long time.");
    boolean log = false;
    if (Common.getInstance().getMainConfig().getBoolean("System.Logging.Enabled")) {
        Common.getInstance().getMainConfig().setValue("System.Logging.Enabled", false);
        log = true;
    }
    JSONArray accounts = (JSONArray) jsonObject.get("accounts");
    iterator = accounts.iterator();
    while (iterator.hasNext()) {
        JSONObject obj = iterator.next();
        String name = (String) obj.get("name");
        Account account = null;
        if (name.startsWith("bank:")) {
            account = engine.getAccount(name.split(":")[1], true, false);
        } else {
            account = engine.getAccount(name, false, false);
        }
        engine.setIgnoreACL(account, (Boolean) obj.get("ignoreACL"));
        engine.setInfiniteMoney(account, (Boolean) obj.get("infiniteMoney"));
        if (obj.get("uuid") != null) {
            engine.updateUUID(account.getAccountName(), UUID.fromString((String) obj.get("uuid")));
        }

        JSONArray balances = (JSONArray) obj.get("balances");
        Iterator<JSONObject> internalIterator = balances.iterator();
        while (internalIterator.hasNext()) {
            JSONObject internalObj = internalIterator.next();
            Currency currency = engine
                    .getCurrency(currenciesMap.get(((Long) internalObj.get("currency_id")).intValue()));
            if (currency != null) {
                engine.setBalance(account, (double) internalObj.get("balance"), currency,
                        (String) internalObj.get("worldName"));
            }
        }

        JSONArray logs = (JSONArray) obj.get("logs");
        internalIterator = logs.iterator();
        while (internalIterator.hasNext()) {
            JSONObject internalObj = internalIterator.next();
            engine.saveLog(LogInfo.valueOf((String) internalObj.get("type")),
                    Cause.valueOf((String) internalObj.get("cause")), (String) internalObj.get("causeReason"),
                    account, (double) internalObj.get("amount"),
                    engine.getCurrency((String) internalObj.get("currencyName")),
                    (String) internalObj.get("worldName"), (Timestamp) internalObj.get("timestamp"));
        }

        JSONArray acls = (JSONArray) obj.get("acls");
        internalIterator = acls.iterator();
        while (internalIterator.hasNext()) {
            JSONObject internalObj = internalIterator.next();
            //{"owner":true,"balance":true,"playerName":"khron_nexx","deposit":true,"acl":true,"withdraw":true}
            engine.saveACL(account, (String) internalObj.get("playerName"),
                    (boolean) internalObj.get("deposit"), (boolean) internalObj.get("withdraw"),
                    (boolean) internalObj.get("acl"), (boolean) internalObj.get("balance"),
                    (boolean) internalObj.get("owner"));
        }

    }
    if (log) {
        Common.getInstance().getMainConfig().setValue("System.Logging.Enabled", true);
    }
    Common.getInstance().sendConsoleMessage(Level.INFO, "Converting done!");
}

From source file:com.hybris.oms.rest.resources.TmallMQ2TestEnvResource.java

@SuppressWarnings("unchecked")
@GET//from w w  w.  j a  v  a 2s .  c o m
@Path("/sendmq2testenv")
@Secured({ "ROLE_admin" })
public String sendMQ2TestEnv() {
    final List<Message> messageList = sendTmallMessageRelatedConfig.getTmallMessageList();

    // Mock Message

    Map<String, Object> rawMap = null;
    Map<String, String> contentMap = null;
    Message message = null;

    Class c;
    try {
        c = Class.forName("com.taobao.api.internal.tmc.Message");
        final Method methodSetRaw = c.getDeclaredMethod("setRaw", Map.class);
        methodSetRaw.setAccessible(true);
        final Object tmallMessageObj = c.newInstance();

        rawMap = new HashMap<String, Object>();
        contentMap = new HashMap<String, String>();
        contentMap.put("buyer_nick", "sandbox_cilai_c");
        contentMap.put("payment", "44.00");
        contentMap.put("tid", "192559684481084");
        contentMap.put("oid", "192559684481084");
        contentMap.put("seller_nick", "sandbox_c_1");
        contentMap.put("type", "guarantee_trade");

        rawMap.put("content", contentMap);
        rawMap.put("topic", "taobao_trade_TradeBuyerPay");
        rawMap.put("time", Calendar.getInstance().getTime());
        rawMap.put("id", "2130700002172846269");
        rawMap.put("nick", "sandbox_c_1");
        rawMap.put("userid", "2074082786");
        rawMap.put("dataid", "192559684481084");
        rawMap.put("publisher", "4272");
        rawMap.put("outtime", Calendar.getInstance().getTime());

        methodSetRaw.invoke(tmallMessageObj, rawMap);
        message = (Message) tmallMessageObj;

        message.setId(4160600490938325004L);
        message.setTopic("taobao_trade_TradeBuyerPay");
        message.setPubTime(Calendar.getInstance().getTime());
        message.setOutgoingTime(Calendar.getInstance().getTime());
        message.setUserId(911757567L);
        message.setContentMap(contentMap);

        messageList.add(message);
    } catch (final Exception e1) {
        logger.error("message reflec error ", e1);
    }

    try {
        // messageNum = messageList.size();

        // ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        // String json = "";
        // json = ow.writeValueAsString(messageList.get(0).getRaw());

        final JSONSerializer jsonSerializer = new JSONSerializer();
        final String rawJson = jsonSerializer.deepSerialize(messageList.get(0).getRaw());

        // ClientResponse response = sendTmallMessageRelatedConfig.getPostmq2testenvWR().header("X-tenantid", "single")
        // .post(ClientResponse.class, rawJson);

        final ClientResponse response = sendTmallMessageRelatedConfig.getReceivemqWR()
                .type(MediaType.APPLICATION_JSON).header("X-tenantid", "single")
                .post(ClientResponse.class, rawJson);

        if (response.getStatus() != 200) {
            logger.debug("Failed : HTTP error code : " + response.getStatus());
        } else {
            messageList.clear();
        }

        logger.info("Output from test env .... \n");
        final String output = response.getEntity(String.class);
        logger.info("Receive " + output + " messages.");

    } catch (final Exception e) {
        logger.error("Fail to send to test env ", e);
    }

    // return messageNum + " messages are sent to test env.";
    return "1 messages are sent to test env.";

}

From source file:cn.powerdash.libsystem.common.exception.AbstractExceptionHandler.java

private String getJsonNameFromMethod(final Field errorField, Class<?> dtoClass) {
    /** find annotation from get/set method........ **/
    String methodName = "set" + errorField.getName().substring(0, 1).toUpperCase()
            + errorField.getName().substring(1);
    try {//  www  . j  ava2s .  c om
        Method method = dtoClass.getDeclaredMethod(methodName, errorField.getType());
        method.setAccessible(true);
        JsonProperty jsonProperty2 = method.getAnnotation(JsonProperty.class);
        if (jsonProperty2 != null) {
            String jp = jsonProperty2.value();
            LOGGER.debug("JsonProperty from SetMethod ===== " + jp);
            return jp;
        }
    } catch (NoSuchMethodException e) {
        LOGGER.debug("NoSuchMethodException {}, try to get JsonProperty from super class", methodName);
        try {
            /**
             * Get JsonProperty from super class. It is only a simple implementation base on one assumption that
             * super class should exist this field. It does not process recursion.
             * **/
            Method method = dtoClass.getSuperclass().getDeclaredMethod(methodName, errorField.getType());
            method.setAccessible(true);
            JsonProperty jsonProperty2 = method.getAnnotation(JsonProperty.class);
            if (jsonProperty2 != null) {
                String jp = jsonProperty2.value();
                LOGGER.debug("JsonProperty from Super {} `s SetMethod ===== {} ", dtoClass.getSuperclass(), jp);
                return jp;
            }
        } catch (Exception ex) { // NOSONAR
            LOGGER.debug(e.getMessage());
        }
    } catch (SecurityException e) {
        LOGGER.debug(e.getMessage());
    }
    return null;
}

From source file:it.cnr.icar.eric.client.admin.AdminShellFactory.java

/**
* Creates the instance of the pluginClass
*//*  ww  w . ja v  a  2s .co  m*/
private Object createPluginInstance(String pluginClass) throws Exception {
    Object plugin = null;

    log.debug("adminShellClass = " + pluginClass);

    Class<?> theClass = Class.forName(pluginClass);

    //try to invoke constructor using Reflection,
    //if this fails then try invoking getInstance()
    try {
        Constructor<?> constructor = theClass.getConstructor((java.lang.Class[]) null);
        plugin = constructor.newInstance(new Object[0]);
    } catch (Exception e) {
        log.warn(rb.getString(AdminShell.ADMIN_SHELL_RESOURCES_PREFIX + "noAccessibleConstructor"));

        Method factory = theClass.getDeclaredMethod("getInstance", (java.lang.Class[]) null);
        plugin = factory.invoke(null, new Object[0]);
    }

    return plugin;
}

From source file:net.rptools.maptool.client.MapTool.java

/**
 * If we're running on OSX we should call this method to download and
 * install the MapTool logo from the main web site. We cache this image so
 * that it appears correctly if the application is later executed in
 * "offline" mode, so to speak./*from  ww  w .  ja v  a2  s .  c  o  m*/
 */
private static void macOSXicon() {
    // If we're running on OSX, add the dock icon image
    // -- and change our application name to just "MapTool" (not currently)
    // We wait until after we call initialize() so that the asset and image managers
    // are configured.
    Image img = null;
    File logoFile = new File(AppUtil.getAppHome("config"), "maptool-dock-icon.png");
    URL logoURL = null;
    try {
        logoURL = new URL("http://www.rptools.net/images/logo/RPTools_Map_Logo.png");
    } catch (MalformedURLException e) {
        showError("Attemping to form URL -- shouldn't happen as URL is hard-coded", e);
    }
    try {
        img = ImageUtil.bytesToImage(FileUtils.readFileToByteArray(logoFile));
    } catch (IOException e) {
        log.debug("Attemping to read cached icon: " + logoFile, e);
        try {
            img = ImageUtil.bytesToImage(FileUtil.getBytes(logoURL));
            // If we did download the logo, save it to the 'config' dir for later use.
            BufferedImage bimg = ImageUtil.createCompatibleImage(img, img.getWidth(null), img.getHeight(null),
                    null);
            FileUtils.writeByteArrayToFile(logoFile, ImageUtil.imageToBytes(bimg, "png"));
            img = bimg;
        } catch (IOException e1) {
            log.warn("Cannot read '" + logoURL + "' or  cached '" + logoFile + "'; no dock icon", e1);
        }
    }
    /*
     * Unfortunately the next line doesn't allow Eclipse to compile the code
     * on anything but a Mac. Too bad because there's no problem at runtime
     * since this code wouldn't be executed an any machine *except* a Mac.
     * Sigh.
     * 
     * com.apple.eawt.Application appl =
     * com.apple.eawt.Application.getApplication();
     */
    try {
        Class<?> appClass = Class.forName("com.apple.eawt.Application");
        Method getApplication = appClass.getDeclaredMethod("getApplication", (Class[]) null);
        Object appl = getApplication.invoke(null, (Object[]) null);
        Method setDockIconImage = appl.getClass().getDeclaredMethod("setDockIconImage",
                new Class[] { java.awt.Image.class });
        // If we couldn't grab the image for some reason, don't set the dock bar icon!  Duh!
        if (img != null)
            setDockIconImage.invoke(appl, new Object[] { img });

        if (MapToolUtil.isDebugEnabled()) {
            // For some reason Mac users don't like the dock badge icon.  But from a development standpoint I like seeing the
            // version number in the dock bar.  So we'll only include it when running with MAPTOOL_DEV on the command line.
            Method setDockIconBadge = appl.getClass().getDeclaredMethod("setDockIconBadge",
                    new Class[] { java.lang.String.class });
            String vers = getVersion();
            vers = vers.substring(vers.length() - 2);
            vers = vers.replaceAll("[^0-9]", "0"); // Convert all non-digits to zeroes
            setDockIconBadge.invoke(appl, new Object[] { vers });
        }
    } catch (Exception e) {
        log.info(
                "Cannot find/invoke methods on com.apple.eawt.Application; use -X command line options to set dock bar attributes",
                e);
    }
}

From source file:it.cnr.icar.eric.server.repository.RepositoryManagerFactory.java

/**
* Creates the instance of the pluginClass
*///  ww w .j  av  a 2s  .  co  m
private Object createPluginInstance(String pluginClass) throws Exception {
    Object plugin = null;

    if (log.isDebugEnabled()) {
        log.debug("pluginClass = " + pluginClass);
    }

    Class<?> theClass = Class.forName(pluginClass);

    //try to invoke constructor using Reflection, 
    //if this fails then try invoking getInstance()
    try {
        Constructor<?> constructor = theClass.getConstructor((java.lang.Class[]) null);
        plugin = constructor.newInstance(new Object[0]);
    } catch (Exception e) {
        //log.trace(ServerResourceBundle.getInstance().getString("message.NoAccessibleConstructor"));

        Method factory = theClass.getDeclaredMethod("getInstance", (java.lang.Class[]) null);
        plugin = factory.invoke(null, new Object[0]);
    }

    return plugin;
}