Example usage for java.lang Float MAX_VALUE

List of usage examples for java.lang Float MAX_VALUE

Introduction

In this page you can find the example usage for java.lang Float MAX_VALUE.

Prototype

float MAX_VALUE

To view the source code for java.lang Float MAX_VALUE.

Click Source Link

Document

A constant holding the largest positive finite value of type float , (2-2-23)·2127.

Usage

From source file:com.spoiledmilk.ibikecph.navigation.routing_engine.SMRoute.java

private boolean isTooFarFromRouteSegment(Location loc, SMTurnInstruction turnA, SMTurnInstruction turnB,
        double maxDistance) {
    double min = Float.MAX_VALUE;

    for (int i = lastVisitedWaypointIndex; i < turnB.waypointsIndex; i++) {
        try {/*from ww  w  .  ja va 2 s.  c o m*/
            Location a = waypoints.get(i);
            Location b = waypoints.get(i + 1);
            double d = SMGPSUtil.distanceFromLineInMeters(loc, a, b);
            if (d < 0.0)
                continue;
            if (d <= min) {
                min = d;
                lastVisitedWaypointIndex = i;
            }
            if (min < 2) {
                // Close enough :)
                break;
            }
        } catch (Exception e) {
            continue;
        }
    }

    if (min <= maxDistance && min < distanceFromRoute) {
        distanceFromRoute = (float) min;

        Location a = waypoints.get(lastVisitedWaypointIndex);
        Location b = waypoints.get(lastVisitedWaypointIndex + 1);
        Location coord = SMGPSUtil.closestCoordinate(loc, a, b);
        if (a.distanceTo(b) > 0.0f) {
            lastCorrectedHeading = SMGPSUtil.bearingBetween(a, b);
        }

        if (visitedLocations != null && visitedLocations.size() > 0) {
            lastCorrectedLocation = new Location(loc);
            lastCorrectedLocation.setLatitude(coord.getLatitude());
            lastCorrectedLocation.setLongitude(coord.getLongitude());
        }
    }

    return min > maxDistance;
}

From source file:trendplot.TrendPlot.java

private void findMinMax(String datFileName) throws FileNotFoundException, IOException {
    File datFile = new File(datFileName);
    try (BufferedInputStream ins = new BufferedInputStream(new FileInputStream(datFile))) {
        boolean eof = false;
        min = Float.MAX_VALUE;
        minMax = Float.MIN_VALUE;
        max = Float.MIN_VALUE;/*from   ww  w  .j av a 2s .  c om*/
        maxMin = Float.MAX_VALUE;
        tmin = Float.MAX_VALUE;
        tmax = Float.MIN_VALUE;
        byte[] b = new byte[Float.SIZE / 8];
        int count = 0;
        int nread;
        while (!eof) {
            try {
                nread = ins.read(b);
                float time = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                nread += ins.read(b);
                float inmin = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                nread += ins.read(b);
                float mean = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                nread += ins.read(b);
                float inmax = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                if (nread == Float.SIZE / 8 * 4) {
                    count++;
                    tmin = Math.min(tmin, time);
                    tmax = Math.max(tmax, time);
                    min = Math.min(min, inmin);
                    minMax = Math.max(minMax, inmin);
                    max = Math.max(max, inmax);
                    maxMin = Math.min(maxMin, inmax);
                } else {
                    eof = true;
                    ins.close();
                }
            } catch (EOFException ex) {
                eof = true;
                ins.close();
            } catch (IOException ex) {
                ins.close();
                throw ex;
            }
        }
    }
}

From source file:de.walware.statet.r.core.rsource.ast.RAst.java

public static Float toJavaFloat(RAstNode node) {
    while (node != null) {
        switch (node.getNodeType()) {
        case NUM_CONST:
            switch (node.getOperator(0)) {
            case NUM_NUM: {
                final Double num = parseNum(node.getText());
                if (num != null && Math.abs(num.doubleValue()) <= Float.MAX_VALUE) {
                    return num.floatValue();
                }// w  w  w  .j a  v a  2s  .  c  om
                break;
            }
            case NUM_INT: {
                final Integer num = parseInt(node.getText());
                if (num != null) {
                    return num.floatValue();
                }
                break;
            }
            case TRUE:
                return 1f;
            case FALSE:
                return 0f;
            default:
                break;
            }
            return null;
        case F_CALL_ARG:
            node = ((FCall.Arg) node).getValueChild();
            continue;
        default:
            return null;
        }
    }
    return null;
}

From source file:com.oguzbabaoglu.cardpager.CardPager.java

private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) {

    if (pagerAdapter == null) {
        return;//from   ww  w  .j  a  v a  2  s.c  o  m
    }

    final int adapterCount = pagerAdapter.getCount();
    final float marginOffset = 0;
    // Fix up offsets for later layout.
    if (oldCurInfo != null) {
        final int oldCurPosition = oldCurInfo.position;
        // Base offsets off of oldCurInfo.
        if (oldCurPosition < curItem.position) {
            int itemIndex = 0;
            ItemInfo ii;
            float offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset;
            for (int pos = oldCurPosition + 1; pos <= curItem.position && itemIndex < items.size(); pos++) {
                ii = items.get(itemIndex);
                while (pos > ii.position && itemIndex < items.size() - 1) {
                    itemIndex++;
                    ii = items.get(itemIndex);
                }
                while (pos < ii.position) {
                    // We don't have an item populated for this,
                    // ask the adapter for an offset.
                    offset += pagerAdapter.getPageWidth(pos) + marginOffset;
                    pos++;
                }
                ii.offset = offset;
                offset += ii.widthFactor + marginOffset;
            }
        } else if (oldCurPosition > curItem.position) {
            int itemIndex = items.size() - 1;
            ItemInfo ii;
            float offset = oldCurInfo.offset;
            for (int pos = oldCurPosition - 1; pos >= curItem.position && itemIndex >= 0; pos--) {
                ii = items.get(itemIndex);
                while (pos < ii.position && itemIndex > 0) {
                    itemIndex--;
                    ii = items.get(itemIndex);
                }
                while (pos > ii.position) {
                    // We don't have an item populated for this,
                    // ask the adapter for an offset.
                    offset -= pagerAdapter.getPageWidth(pos) + marginOffset;
                    pos--;
                }
                offset -= ii.widthFactor + marginOffset;
                ii.offset = offset;
            }
        }
    }

    // Base all offsets off of curItem.
    final int itemCount = items.size();
    float offset = curItem.offset;
    int pos = curItem.position - 1;
    firstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE;
    lastOffset = curItem.position == adapterCount - 1 ? curItem.offset + curItem.widthFactor - 1
            : Float.MAX_VALUE;
    // Previous pages
    for (int i = curIndex - 1; i >= 0; i--, pos--) {
        final ItemInfo ii = items.get(i);
        while (pos > ii.position) {
            offset -= pagerAdapter.getPageWidth(pos--) + marginOffset;
        }
        offset -= ii.widthFactor + marginOffset;
        ii.offset = offset;
        if (ii.position == 0) {
            firstOffset = offset;
        }
    }
    offset = curItem.offset + curItem.widthFactor + marginOffset;
    pos = curItem.position + 1;
    // Next pages
    for (int i = curIndex + 1; i < itemCount; i++, pos++) {
        final ItemInfo ii = items.get(i);
        while (pos < ii.position) {
            offset += pagerAdapter.getPageWidth(pos++) + marginOffset;
        }
        if (ii.position == adapterCount - 1) {
            lastOffset = offset + ii.widthFactor - 1;
        }
        ii.offset = offset;
        offset += ii.widthFactor + marginOffset;
    }
}

From source file:MSUmpire.FragmentLib.FragmentLibManager.java

public void ImportFragLibBySPTXT(String sptxtpath) throws IOException, XmlPullParserException {
    Logger.getRootLogger().info("Parsing " + sptxtpath);
    try {//from w  ww. java  2 s . c om
        BufferedReader reader = new BufferedReader(new FileReader(sptxtpath));

        PTMManager.GetInstance();

        String line = "";
        boolean Header = false;
        boolean Peak = false;
        PepFragmentLib fraglib = null;
        ArrayList<FragmentPeak> FragmentPeaks = null;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("#")) {
                continue;
            } else if (line.startsWith("Name:")) {
                Header = true;
                fraglib = new PepFragmentLib();
                FragmentPeaks = new ArrayList<>();
            } else if (line.startsWith("FullName:") && Header) {
                String temp = line.substring(line.indexOf(".") + 1);
                String modstring = temp.substring(0, temp.indexOf("."));
                fraglib.Sequence = modstring.replace("n[", "[").replace("c[", "").replaceAll("[\\[0-9\\]]", "");
                fraglib.ModSequence = ModStringConvert.ConvertTPPModString(modstring, fraglib.Modifications);
                fraglib.Charge = Integer.parseInt(line.split("/")[1].subSequence(0, 1).toString());
            } else if (line.startsWith("Comment:") && Header) {
                //String RTs = line.split("RetentionTime=")[1].split(" ")[0];
                String RTs = line.split("iRT=")[1].split(" ")[0];
                for (String rt : RTs.split(",")) {
                    //fraglib.RetentionTime.add(Float.parseFloat(rt)/60f);
                    fraglib.RetentionTime.add(Float.parseFloat(rt));
                }
            } else if (line.startsWith("PrecursorMZ:") && Header) {
                fraglib.PrecursorMz = Float.parseFloat(line.split(":")[1].trim());
            } else if (line.startsWith("NumPeaks:") && Header) {
                Peak = true;
            } else if (!"".equals(line) && Peak) {
                String mz = line.split("\t")[0];
                String intensity = line.split("\t")[1];
                String type = line.split("\t")[2];

                FragmentPeak fragment = new FragmentPeak();
                fragment.IonType = "?";
                float delta = Float.MAX_VALUE;
                String iontype = "";
                for (String ion : type.split(",")) {
                    if (ion.startsWith("b") || ion.startsWith("y")) {
                        String temp = ion.split("/")[0].split("-")[0];
                        if (temp.contains("^")) {
                            fragment.IonType = temp.substring(0, temp.indexOf("^"));
                        } else {
                            fragment.IonType = temp.replace("i", "");
                        }
                        break;
                    }
                    fragment.FragMZ = Float.parseFloat(mz.trim());
                    fragment.intensity = Float.parseFloat(intensity.trim());
                    fragment.Charge = 1;
                    FragmentPeaks.add(fragment);
                }
            } else if ("".equals(line) && Peak) {
                Header = false;
                Peak = false;
                fraglib.AddFragments(FragmentPeaks);
                PeptideFragmentLib.put(fraglib.GetKey(), fraglib);
            }
        }
        Logger.getRootLogger().info("No. of peptide ions in the imported library:" + PeptideFragmentLib.size());
        GenerateDecoyLib();
    } catch (MatrixLoaderException ex) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
    }
}

From source file:com.telefonica.iot.cygnus.sinks.NGSICartoDBSink.java

private void persistDistanceEvent(NGSIEvent event) throws CygnusBadConfiguration, CygnusPersistenceError {
    // Get some values
    String schema = buildSchemaName(event.getServiceForNaming(enableNameMappings));
    String service = event.getServiceForData();
    String servicePath = event.getServicePathForData();
    String entityId = event.getContextElement().getId();
    String entityType = event.getContextElement().getType();

    // Iterate on all this context element attributes, if there are attributes
    ArrayList<ContextAttribute> contextAttributes = event.getContextElement().getAttributes();

    if (contextAttributes == null || contextAttributes.isEmpty()) {
        return;/*from  w w w .j  a  va  2 s  .  com*/
    } // if

    ((CartoDBBackendImpl) backends.get(schema)).startTransaction();

    for (ContextAttribute contextAttribute : contextAttributes) {
        long recvTimeTs = event.getRecvTimeTs();
        String attrType = contextAttribute.getType();
        String attrValue = contextAttribute.getContextValue(false);
        String attrMetadata = contextAttribute.getContextMetadata();
        ImmutablePair<String, Boolean> location = NGSIUtils.getGeometry(attrValue, attrType, attrMetadata,
                swapCoordinates);
        String tableName = buildTableName(event.getServicePathForNaming(enableGrouping, enableNameMappings),
                event.getEntityForNaming(enableGrouping, enableNameMappings, enableEncoding),
                event.getAttributeForNaming(enableNameMappings)) + CommonConstants.CONCATENATOR + "distance";

        if (location.getRight()) {
            // Try creating the table... the cost of checking if it exists and creating it is higher than directly
            // attempting to create it. If existing, nothing will be re-created and the new values will be inserted

            try {
                String typedFields = "(recvTimeMs bigint, fiwareServicePath text, entityId text, entityType text, "
                        + "stageDistance float, stageTime float, stageSpeed float, sumDistance float, "
                        + "sumTime float, sumSpeed float, sum2Distance float, sum2Time float, sum2Speed float, "
                        + "maxDistance float, minDistance float, maxTime float, minTime float, maxSpeed float, "
                        + "minSpeed float, numSamples bigint)";
                backends.get(schema).createTable(schema, tableName, typedFields);

                // Once created, insert the first row
                String withs = "";
                String fields = "(recvTimeMs, fiwareServicePath, entityId, entityType, the_geom, stageDistance,"
                        + "stageTime, stageSpeed, sumDistance, sumTime, sumSpeed, sum2Distance, sum2Time,"
                        + "sum2Speed, maxDistance, minDistance, maxTime, mintime, maxSpeed, minSpeed, numSamples)";
                String rows = "(" + recvTimeTs + ",'" + servicePath + "','" + entityId + "','" + entityType
                        + "'," + location.getLeft() + ",0,0,0,0,0,0,0,0,0," + Float.MIN_VALUE + ","
                        + Float.MAX_VALUE + "," + Float.MIN_VALUE + "," + Float.MAX_VALUE + ","
                        + Float.MIN_VALUE + "," + Float.MAX_VALUE + ",1)";
                LOGGER.info("[" + this.getName() + "] Persisting data at NGSICartoDBSink. Schema (" + schema
                        + "), Table (" + tableName + "), Data (" + rows + ")");
                backends.get(schema).insert(schema, tableName, withs, fields, rows);
            } catch (Exception e1) {
                String withs = "" + "WITH geom AS (" + "   SELECT " + location.getLeft() + " AS point"
                        + "), calcs AS (" + "   SELECT" + "      cartodb_id,"
                        + "      ST_Distance(the_geom::geography, geom.point::geography) AS stage_distance,"
                        + "      (" + recvTimeTs + " - recvTimeMs) AS stage_time" + "   FROM " + tableName
                        + ", geom" + "   ORDER BY cartodb_id DESC" + "   LIMIT 1" + "), speed AS ("
                        + "   SELECT"
                        + "      (calcs.stage_distance / NULLIF(calcs.stage_time, 0)) AS stage_speed"
                        + "   FROM calcs" + "), inserts AS (" + "   SELECT"
                        + "      (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) AS sum_dist,"
                        + "      (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) AS sum_time,"
                        + "      (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) AS sum_speed,"
                        + "      (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) "
                        + "          * (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) AS sum2_dist,"
                        + "      (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) "
                        + "          * (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) AS sum2_time,"
                        + "      (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) "
                        + "          * (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) AS sum2_speed,"
                        + "      t1.max_distance," + "      t1.min_distance," + "      t1.max_time,"
                        + "      t1.min_time," + "      t1.max_speed," + "      t1.min_speed,"
                        + "      t2.num_samples" + "   FROM" + "      (" + "         SELECT"
                        + "            GREATEST(calcs.stage_distance, maxDistance) AS max_distance,"
                        + "            LEAST(calcs.stage_distance, minDistance) AS min_distance,"
                        + "            GREATEST(calcs.stage_time, maxTime) AS max_time,"
                        + "            LEAST(calcs.stage_time, minTime) AS min_time,"
                        + "            GREATEST(speed.stage_speed, maxSpeed) AS max_speed,"
                        + "            LEAST(speed.stage_speed, minSpeed) AS min_speed,"
                        + "            sumDistance," + "            sumTime," + "            sumSpeed"
                        + "         FROM " + tableName + ", speed, calcs" + "         ORDER BY " + tableName
                        + ".cartodb_id DESC" + "         LIMIT 1" + "      ) AS t1," + "      ("
                        + "         SELECT (-1 * ((-1 * COUNT(*)) - 1)) AS num_samples" + "         FROM "
                        + tableName + "      ) AS t2," + "      speed," + "      calcs" + ")";
                String fields = "(recvTimeMs, fiwareServicePath, entityId, entityType, the_geom, stageDistance,"
                        + "stageTime, stageSpeed, sumDistance, sumTime, sumSpeed, sum2Distance, sum2Time,"
                        + "sum2Speed, maxDistance, minDistance, maxTime, mintime, maxSpeed, minSpeed, numSamples)";
                String rows = "(" + recvTimeTs + ",'" + servicePath + "','" + entityId + "','" + entityType
                        + "'," + "(SELECT point FROM geom),(SELECT stage_distance FROM calcs),"
                        + "(SELECT stage_time FROM calcs),(SELECT stage_speed FROM speed),"
                        + "(SELECT sum_dist FROM inserts),(SELECT sum_time FROM inserts),"
                        + "(SELECT sum_speed FROM inserts),(SELECT sum2_dist FROM inserts),"
                        + "(SELECT sum2_time FROM inserts),(SELECT sum2_speed FROM inserts),"
                        + "(SELECT max_distance FROM inserts),(SELECT min_distance FROM inserts),"
                        + "(SELECT max_time FROM inserts),(SELECT min_time FROM inserts),"
                        + "(SELECT max_speed FROM inserts),(SELECT min_speed FROM inserts),"
                        + "(SELECT num_samples FROM inserts))";
                LOGGER.info("[" + this.getName() + "] Persisting data at NGSICartoDBSink. Schema (" + schema
                        + "), Table (" + tableName + "), Data (" + rows + ")");

                try {
                    backends.get(schema).insert(schema, tableName, withs, fields, rows);
                } catch (Exception e2) {
                    ImmutablePair<Long, Long> bytes = ((CartoDBBackendImpl) backends.get(schema))
                            .finishTransaction();
                    serviceMetrics.add(service, servicePath, 0, 0, 0, 0, 0, 0, bytes.left, bytes.right, 0);
                    throw new CygnusPersistenceError("-, " + e2.getMessage());
                } // try catch
            } // try catch
        } // if
    } // for

    ImmutablePair<Long, Long> bytes = ((CartoDBBackendImpl) backends.get(schema)).finishTransaction();
    serviceMetrics.add(service, servicePath, 0, 0, 0, 0, 0, 0, bytes.left, bytes.right, 0);
}

From source file:gov.nist.itl.versus.similarity.transforms.ColorModels.java

public boolean convertGRAY2RGBOut(ImageObject image, ImageObject newIm) {
    if (image == null || image.getNumCols() <= 0 || image.getNumRows() <= 0) {
        logger.debug("ERROR: no image \n");

        return false;
    }/*from  www.  j a  v a 2  s  .c  o m*/

    if (image.getNumBands() != 1) {
        logger.debug("ERROR: input images should have sampPerPixel = 1");

        return false;
    }

    if (image.getType() != ImageObject.TYPE_BYTE && image.getType() != ImageObject.TYPE_FLOAT) {
        logger.debug("ERROR: image type is not supported");

        return false;
    }

    ///
    if (newIm == null || newIm.getNumCols() != image.getNumCols() || newIm.getNumRows() != image.getNumRows()) {

        logger.debug("ERROR: no image or mismatch of size \n");

        return false;

    }

    if (newIm.getNumBands() != 3) {
        logger.debug("ERROR: input images should have sampPerPixel = 3");

        return false;
    }

    if (image.getType() != newIm.getType()) {
        logger.debug("ERROR: image and outImage types are inconsistent");

        return false;
    }

    int numrows, numcols;
    numrows = image.getNumRows();
    numcols = image.getNumCols();

    //long size = newIm.size;
    _MaxVal = -Float.MAX_VALUE;//-5000; // int values
    _MinVal = Float.MAX_VALUE;//5000;
    int index, indexColor;
    boolean signal = true;

    float val;

    for (index = 0, indexColor = 0; index < image.getSize(); index++, indexColor += 3) {
        val = image.getFloat(index);
        newIm.setFloat(indexColor, val);
        newIm.setFloat(indexColor + 1, val);
        newIm.setFloat(indexColor + 2, val);

        if (val > _MaxVal)
            _MaxVal = val;

        if (val < _MinVal)
            _MinVal = val;
    }

    signal = false;

    if (signal)
        return false;

    logger.debug("Max val in PGM = " + _MaxVal);
    logger.debug("Min val in PGM = " + _MinVal);

    return true;//(newIm);
}

From source file:org.springframework.beans.AbstractPropertyAccessorTests.java

@Test
public void setPrimitiveProperties() {
    NumberPropertyBean target = new NumberPropertyBean();
    AbstractPropertyAccessor accessor = createAccessor(target);

    String byteValue = " " + Byte.MAX_VALUE + " ";
    String shortValue = " " + Short.MAX_VALUE + " ";
    String intValue = " " + Integer.MAX_VALUE + " ";
    String longValue = " " + Long.MAX_VALUE + " ";
    String floatValue = " " + Float.MAX_VALUE + " ";
    String doubleValue = " " + Double.MAX_VALUE + " ";

    accessor.setPropertyValue("myPrimitiveByte", byteValue);
    accessor.setPropertyValue("myByte", byteValue);

    accessor.setPropertyValue("myPrimitiveShort", shortValue);
    accessor.setPropertyValue("myShort", shortValue);

    accessor.setPropertyValue("myPrimitiveInt", intValue);
    accessor.setPropertyValue("myInteger", intValue);

    accessor.setPropertyValue("myPrimitiveLong", longValue);
    accessor.setPropertyValue("myLong", longValue);

    accessor.setPropertyValue("myPrimitiveFloat", floatValue);
    accessor.setPropertyValue("myFloat", floatValue);

    accessor.setPropertyValue("myPrimitiveDouble", doubleValue);
    accessor.setPropertyValue("myDouble", doubleValue);

    assertEquals(Byte.MAX_VALUE, target.getMyPrimitiveByte());
    assertEquals(Byte.MAX_VALUE, target.getMyByte().byteValue());

    assertEquals(Short.MAX_VALUE, target.getMyPrimitiveShort());
    assertEquals(Short.MAX_VALUE, target.getMyShort().shortValue());

    assertEquals(Integer.MAX_VALUE, target.getMyPrimitiveInt());
    assertEquals(Integer.MAX_VALUE, target.getMyInteger().intValue());

    assertEquals(Long.MAX_VALUE, target.getMyPrimitiveLong());
    assertEquals(Long.MAX_VALUE, target.getMyLong().longValue());

    assertEquals(Float.MAX_VALUE, target.getMyPrimitiveFloat(), 0.001);
    assertEquals(Float.MAX_VALUE, target.getMyFloat().floatValue(), 0.001);

    assertEquals(Double.MAX_VALUE, target.getMyPrimitiveDouble(), 0.001);
    assertEquals(Double.MAX_VALUE, target.getMyDouble().doubleValue(), 0.001);

}

From source file:org.apache.poi.util.MethodUtils.java

/**
 * <p>Find an accessible method that matches the given name and has compatible parameters.
 * Compatible parameters mean that every method parameter is assignable from 
 * the given parameters.//from w  ww .java2  s  .c  o  m
 * In other words, it finds a method with the given name 
 * that will take the parameters given.<p>
 *
 * <p>This method is slightly undeterminstic since it loops 
 * through methods names and return the first matching method.</p>
 * 
 * <p>This method is used by 
 * {@link 
 * #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
 *
 * <p>This method can match primitive parameter by passing in wrapper classes.
 * For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
 * parameter.
 *
 * @param clazz find method in this class
 * @param methodName find method with this name
 * @param parameterTypes find method with compatible parameters 
 * @return The accessible method
 */
public static Method getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) {
    // trace logging
    Log log = LogFactory.getLog(MethodUtils.class);
    if (log.isTraceEnabled()) {
        log.trace("Matching name=" + methodName + " on " + clazz);
    }
    MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false);

    // see if we can find the method directly
    // most of the time this works and it's much faster
    try {
        Method method = clazz.getMethod(methodName, parameterTypes);
        if (log.isTraceEnabled()) {
            log.trace("Found straight match: " + method);
            log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
        }

        setMethodAccessible(method); // Default access superclass workaround

        return method;

    } catch (NoSuchMethodException e) {
        /* SWALLOW */ }

    // search through all methods 
    int paramSize = parameterTypes.length;
    Method bestMatch = null;
    Method[] methods = clazz.getMethods();
    float bestMatchCost = Float.MAX_VALUE;
    float myCost = Float.MAX_VALUE;
    for (int i = 0, size = methods.length; i < size; i++) {
        if (methods[i].getName().equals(methodName)) {
            // log some trace information
            if (log.isTraceEnabled()) {
                log.trace("Found matching name:");
                log.trace(methods[i]);
            }

            // compare parameters
            Class[] methodsParams = methods[i].getParameterTypes();
            int methodParamSize = methodsParams.length;
            if (methodParamSize == paramSize) {
                boolean match = true;
                for (int n = 0; n < methodParamSize; n++) {
                    if (log.isTraceEnabled()) {
                        log.trace("Param=" + parameterTypes[n].getName());
                        log.trace("Method=" + methodsParams[n].getName());
                    }
                    if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
                        if (log.isTraceEnabled()) {
                            log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]);
                        }
                        match = false;
                        break;
                    }
                }

                if (match) {
                    // get accessible version of method
                    Method method = getAccessibleMethod(clazz, methods[i]);
                    if (method != null) {
                        if (log.isTraceEnabled()) {
                            log.trace(method + " accessible version of " + methods[i]);
                        }
                        setMethodAccessible(method); // Default access superclass workaround
                        myCost = getTotalTransformationCost(parameterTypes, method.getParameterTypes());
                        if (myCost < bestMatchCost) {
                            bestMatch = method;
                            bestMatchCost = myCost;
                        }
                    }

                    log.trace("Couldn't find accessible method.");
                }
            }
        }
    }
    if (bestMatch == null) {
        // didn't find a match
        log.trace("No match found.");
    }

    return bestMatch;
}

From source file:pipeline.misc_util.Utils.java

public static float getMin(IPluginIOHyperstack imageSource) {
    float the_min = Float.MAX_VALUE;
    for (IPluginIOStack channel : imageSource.getChannels().values()) {
        float channelMinimum = getMin(channel);
        if (channelMinimum < the_min)
            the_min = channelMinimum;//ww w . ja v a2 s .c o m
    }
    return the_min;
}