List of usage examples for java.lang.reflect Array getLength
@HotSpotIntrinsicCandidate public static native int getLength(Object array) throws IllegalArgumentException;
From source file:ArrayUtils.java
/** * Gets the elements that are in array1, but not array 2. * // w ww .j a va 2s . c o m * @param array1 * The first array * @param array2 * The second array * @return The elements in <code>array1</code> that do not occur in * <code>array2</code> */ public static Object[] removedElementsP(Object array1, Object array2) { int count = 0; if (array1 == null || array2 == null) return new Object[0]; if (!array1.getClass().isArray() || array2.getClass().isArray()) return new Object[0]; int len1 = Array.getLength(array1); int len2 = Array.getLength(array2); int i, j; for (i = 0; i < len1; i++) { count++; for (j = 0; j < len2; j++) { if (equals(Array.get(array1, i), Array.get(array2, j))) { count--; break; } } } Object[] ret = new Object[count]; count = 0; for (i = 0; i < len1; i++) { count++; for (j = 0; j < len2; j++) { if (equals(Array.get(array1, i), Array.get(array2, j))) { count--; break; } ret[count] = Array.get(array1, i); } } return ret; }
From source file:gedi.util.ArrayUtils.java
/** * Inserts an item into an array and returns a new array * @param <T> the class//from w w w . ja va2s .c om * @param array the array * @param index the index where to insert * @param item the item to insert * @return the new array */ @SuppressWarnings("unchecked") public static <T> T[] insertItemToArray(T[] array, int index, T item) { T[] re = (T[]) Array.newInstance(array.getClass().getComponentType(), Array.getLength(array) + 1); System.arraycopy(array, 0, re, 0, index); re[index] = item; System.arraycopy(array, index, re, index + 1, array.length - index); return re; }
From source file:ArrayUtils.java
/** * Gets the elements that are in array2, but not array 1. * //from w ww.j a v a 2 s . co m * @param array1 * The first array * @param array2 * The second array * @return The elements in <code>array2</code> that do not occur in * <code>array1</code> */ public static Object[] addedElements(Object array1, Object array2) { int count = 0; if (array1 == null || array2 == null) return new Object[0]; if (!array1.getClass().isArray() || array2.getClass().isArray()) return new Object[0]; int len1 = Array.getLength(array1); int len2 = Array.getLength(array2); int i, j; for (i = 0; i < len1; i++) { count++; for (j = 0; j < len2; j++) { if (equals(Array.get(array2, i), Array.get(array1, j))) { count--; break; } } } Object[] ret = new Object[count]; count = 0; for (i = 0; i < len1; i++) { count++; for (j = 0; j < len2; j++) { if (equals(Array.get(array2, i), Array.get(array1, j))) { count--; break; } ret[count] = Array.get(array2, i); } } return ret; }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@SuppressWarnings("unchecked") private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException { net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue( "", null); AfxBeanUtils.copySamePropertyValue(pv2, pv); String propertyName = tokens.canonicalName; String actualName = tokens.actualName; if (tokens.keys != null) { // Apply indexes and map keys: fetch value for all keys but the last one. PropertyTokenHolder getterTokens = new PropertyTokenHolder(); getterTokens.canonicalName = tokens.canonicalName; getterTokens.actualName = tokens.actualName; getterTokens.keys = new String[tokens.keys.length - 1]; System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); Object propValue;/*from ww w .j a v a 2 s. c o m*/ try { propValue = getPropertyValue(getterTokens); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "'", ex); } // Set value for last key. String key = tokens.keys[tokens.keys.length - 1]; if (propValue == null) { // null map value case if (isAutoGrowNestedPaths()) { // #TO#DO#: cleanup, this is pretty hacky int lastKeyIndex = tokens.canonicalName.lastIndexOf('['); getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex); propValue = setDefaultValue(getterTokens); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "': returned null"); } } if (propValue.getClass().isArray()) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class<?> requiredType = propValue.getClass().getComponentType(); int arrayIndex = Integer.parseInt(key); Object oldValue = null; try { if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) { oldValue = Array.get(propValue, arrayIndex); } Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length)); Array.set(propValue, arrayIndex, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid array index in property path '" + propertyName + "'", ex); } } else if (propValue instanceof List) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(), tokens.keys.length); List<Object> list = (List<Object>) propValue; int index = Integer.parseInt(key); Object oldValue = null; if (isExtractOldValueForEditor() && index < list.size()) { oldValue = list.get(index); } Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length)); int size = list.size(); if (index >= size && index < this.autoGrowCollectionLimit) { for (int i = size; i < index; i++) { try { list.add(null); } catch (NullPointerException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot set element with index " + index + " in List of size " + size + ", accessed using property path '" + propertyName + "': List does not support filling up gaps with null elements"); } } list.add(convertedValue); } else { try { list.set(index, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid list index in property path '" + propertyName + "'", ex); } } } else if (propValue instanceof Map) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), tokens.keys.length); Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(), tokens.keys.length); Map<Object, Object> map = (Map<Object, Object>) propValue; // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); Object oldValue = null; if (isExtractOldValueForEditor()) { oldValue = map.get(convertedMapKey); } // Pass full property name and old value in here, since we want full // conversion ability for map values. Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType, TypeDescriptor.nested(property(pd), tokens.keys.length)); map.put(convertedMapKey, convertedMapValue); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]"); } } else { PropertyDescriptor pd = pv.getResolvedDescriptor(); if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) { pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getWriteMethod() == null) { if (pv.isOptional()) { logger.debug("Ignoring optional value for property '" + actualName + "' - property not found on bean class [" + getRootClass().getName() + "]"); return; } else { PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass()); throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, matches.buildErrorMessage(), matches.getPossibleMatches()); } } pv.getOriginalPropertyValue().setResolvedDescriptor(pd); } Object oldValue = null; try { Object originalValue = pv.getValue(); Object valueToApply = originalValue; if (!Boolean.FALSE.equals(pv.getConversionNecessary())) { if (pv.isConverted()) { valueToApply = pv.getConvertedValue(); } else { if (isExtractOldValueForEditor() && pd.getReadMethod() != null) { final Method readMethod = pd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } try { if (System.getSecurityManager() != null) { oldValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(object); } }, acc); } else { oldValue = readMethod.invoke(object); } } catch (Exception ex) { if (ex instanceof PrivilegedActionException) { ex = ((PrivilegedActionException) ex).getException(); } if (logger.isDebugEnabled()) { logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName + "'", ex); } } } valueToApply = convertForProperty(propertyName, oldValue, originalValue, new TypeDescriptor(property(pd))); } pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue); } final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() : pd.getWriteMethod()); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { writeMethod.setAccessible(true); return null; } }); } else { writeMethod.setAccessible(true); } } final Object value = valueToApply; if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { writeMethod.invoke(object, value); return null; } }, acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { writeMethod.invoke(this.object, value); } } catch (TypeMismatchException ex) { throw ex; } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); if (ex.getTargetException() instanceof ClassCastException) { throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); } else { throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); } } catch (Exception ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); throw new MethodInvocationException(pce, ex); } } }
From source file:com.concursive.connect.web.modules.calendar.utils.CalendarView.java
/** * Constructs the calendar and returns a String object with the HTML * * @return The HTML value//from www. j av a 2s . c om */ public String getHtml(String contextPath) { StringBuffer html = new StringBuffer(); //Begin the whole table html.append("<table class='calendarContainer'>" + "<tr><td>"); //Space at top to match if (headerSpace) { html.append("<table width=\"100%\" align=\"center\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">" + "<tr><td> </td></tr>" + "</table>"); } String monthArrowPrev = ""; String monthArrowNext = ""; //If popup, then use small formats of each class String tableWidth = "100%"; String pre = ""; if (popup) { pre = "small"; tableWidth = "155"; } else if (frontPageView) { tableWidth = "auto"; } //Display Calendar html.append("<table height=\"100%\" width='" + tableWidth + "' " + borderSize + cellSpacing + cellPadding + " class='" + pre + "calendar' id='calendarTable'>" + "<tr height=\"4%\">"); //Display Previous Month Arrow if (popup) { monthArrowPrev = "<INPUT TYPE=\"IMAGE\" NAME=\"prev\" ALIGN=\"MIDDLE\" SRC=\"" + contextPath + "/images/calendar/prev_arrow.png\">"; monthArrowNext = "<INPUT TYPE=\"IMAGE\" NAME=\"next\" ALIGN=\"MIDDLE\" SRC=\"" + contextPath + "/images/calendar/next_arrow.png\">"; if (monthArrows) { html.append("<th class='" + pre + "monthArrowPrev'>" + monthArrowPrev + "</th>"); } //Display Current Month name if (monthArrows) { html.append("<th colspan='5' "); } else { html.append("<th colspan='7' "); } html.append("class='" + pre + "monthName'"); html.append("><strong>" + StringUtils.toHtml(this.getMonthName(cal)) + " " + this.getYear(cal) + "</strong></th>"); //Display Next Month Arrow if (monthArrows) { html.append("<th class='" + pre + "monthArrowNext'>" + monthArrowNext + "</th>"); } } else { if (monthArrows) { int prevMonth = calPrev.get(Calendar.MONTH) + 1; String previousLink = calPrev.get(Calendar.YEAR) + "-" + (prevMonth < 10 ? "0" : "") + prevMonth; int nextMonth = calNext.get(Calendar.MONTH) + 1; String nextLink = calNext.get(Calendar.YEAR) + "-" + (nextMonth < 10 ? "0" : "") + nextMonth; html.append("<th colspan='8' "); html.append("class='" + pre + "monthName'"); html.append(">" + "<a href=\"javascript:goToMonth('" + previousLink + "');\"><img ALIGN=\"MIDDLE\" border=\"0\" src=\"" + contextPath + "/images/calendar/prev_arrow.png\" /></a> " + "<strong>" + StringUtils.toHtml(this.getMonthName(cal)) + " " + this.getYear(cal) + "</strong>" + " <a href=\"javascript:goToMonth('" + nextLink + "');\"><img ALIGN=\"MIDDLE\" border=\"0\" src=\"" + contextPath + "/images/calendar/next_arrow.png\" /></a>" + "</th>"); } else { html.append("<th colspan=\"8\">"); html.append(getHtmlMonthSelect()); html.append(" "); html.append(getHtmlYearSelect()); html.append(" "); Calendar tmp = Calendar.getInstance(locale); tmp.set(Calendar.HOUR, 0); tmp.set(Calendar.MINUTE, 0); tmp.set(Calendar.SECOND, 0); tmp.set(Calendar.MILLISECOND, 0); if (timeZone != null) { tmp.setTimeZone(timeZone); } html.append("<a href=\"javascript:showToDaysEvents('" + (tmp.get(Calendar.MONTH) + 1) + "','" + tmp.get(Calendar.DATE) + "','" + tmp.get(Calendar.YEAR) + "');\">Today</a>"); html.append("</th>"); } } html.append("</tr>"); //Display the Days of the Week names html.append("<tr height=\"4%\">"); if (!popup) { html.append("<td width=\"4\" class=\"row1\"><font style=\"visibility:hidden\">n</font></td>"); } // Use locale... int firstDayOfWeek = cal.getFirstDayOfWeek(); for (int i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) { html.append("<td width=\"14%\" class='" + pre + "weekName'>"); if (popup || frontPageView) { html.append(StringUtils.toHtml(this.getDayName(i, true))); } else { html.append(StringUtils.toHtml(this.getDayName(i, false))); } html.append("</td>"); } html.append("</tr>"); int startCellPrev = this.getStartCell(calPrev); int endCellPrev = this.getEndCell(calPrev); int startCell = this.getStartCell(cal); int endCell = this.getEndCell(cal); int thisDay = 1; String tdClass = ""; for (int cellNo = 0; cellNo < this.getNumberOfCells(); cellNo++) { boolean prevMonth = false; boolean nextMonth = false; boolean mainMonth = false; int displayDay = 0; int displayMonth = 0; int displayYear = 0; if (cellNo < startCell) { //The previous month displayMonth = calPrev.get(Calendar.MONTH) + 1; displayYear = calPrev.get(Calendar.YEAR); displayDay = (endCellPrev - startCell + 2 + cellNo - startCellPrev); prevMonth = true; } else if (cellNo > endCell) { //The next month displayMonth = calNext.get(Calendar.MONTH) + 1; displayYear = calNext.get(Calendar.YEAR); if (endCell + 1 == cellNo) { thisDay = 1; } displayDay = thisDay; nextMonth = true; thisDay++; } else { //The main month mainMonth = true; displayMonth = cal.get(Calendar.MONTH) + 1; displayYear = cal.get(Calendar.YEAR); displayDay = thisDay; thisDay++; } if (cellNo % 7 == 0) { tdClass = ""; html.append("<tr"); if (!popup) { if (calendarInfo.getCalendarView().equalsIgnoreCase("week")) { if (displayMonth == calendarInfo.getStartMonthOfWeek() && displayDay == calendarInfo.getStartDayOfWeek()) { html.append(" class=\"selectedWeek\" "); tdClass = "selectedDay"; } } } html.append(">"); } if (!popup && (cellNo % 7 == 0)) { html.append("<td valign='top' width=\"4\" class=\"weekSelector\" name=\"weekSelector\">"); String weekSelectedArrow = "<a href=\"javascript:showWeekEvents('" + displayYear + "','" + displayMonth + "','" + displayDay + "')\">" + "<img ALIGN=\"MIDDLE\" src=\"" + contextPath + "/images/control.png\" border=\"0\" onclick=\"javascript:switchTableClass(this,'selectedWeek','row');\"></a>"; html.append(weekSelectedArrow); html.append("</td>"); } html.append("<td valign='top'"); if (!smallView) { if (!frontPageView) { html.append(" height='70'"); } else { html.append(" height='35'"); } } if (!popup) { html.append(" onclick=\"javascript:showDayEvents('" + displayYear + "','" + displayMonth + "','" + displayDay + "');javascript:switchTableClass(this,'selectedDay','cell');\""); if (calendarInfo.getCalendarView().equalsIgnoreCase("day")) { tdClass = ""; if (displayMonth == calendarInfo.getMonthSelected() && displayDay == calendarInfo.getDaySelected()) { tdClass = "selectedDay"; } } } if (prevMonth) { //The previous month if (this.isCurrentDay(calPrev, displayDay)) { html.append(" id='today' class='" + ((tdClass.equalsIgnoreCase("")) ? pre + "today'" : tdClass + "'") + " name='" + pre + "today' >"); } else { html.append(" class='" + ((tdClass.equalsIgnoreCase("")) ? pre + "noday'" : tdClass + "'") + " name='" + pre + "noday' >"); } } else if (nextMonth) { if (this.isCurrentDay(calNext, displayDay)) { html.append(" id='today' class='" + ((tdClass.equalsIgnoreCase("")) ? pre + "today'" : tdClass + "'") + " name='" + pre + "today' >"); } else { html.append(" class='" + ((tdClass.equalsIgnoreCase("")) ? pre + "noday'" : tdClass + "'") + " name='" + pre + "noday' >"); } } else { //The main main if (this.isCurrentDay(cal, displayDay)) { html.append(" id='today' class='" + ((tdClass.equalsIgnoreCase("")) ? pre + "today'" : tdClass + "'") + " name='" + pre + "today' >"); } else { html.append(" class='" + ((tdClass.equalsIgnoreCase("")) ? pre + "day'" : tdClass + "'") + " name='" + pre + "day' >"); } } // end if block //Display the day in the appropriate link color if (popup) { //Popup calendar CalendarEventList highlightEvent = eventList .get(displayMonth + "/" + displayDay + "/" + displayYear); String dateColor = "" + displayDay; if (highlightEvent != null && highlightEvent.containsKey("highlight")) { dateColor = "<font color=#FF0000>" + displayDay + "</font>"; } else if (!mainMonth) { dateColor = "<font color=#888888>" + displayDay + "</font>"; } html.append("<a href=\"javascript:returnDate(" + displayDay + ", " + displayMonth + ", " + displayYear + ");\"" + ">" + dateColor + "</a>"); } else { //Event calendar String dateColor = "" + displayDay; if (!mainMonth) { dateColor = "<font color=#888888>" + displayDay + "</font>"; } html.append("<a href=\"javascript:showDayEvents('" + displayYear + "','" + displayMonth + "','" + displayDay + "');\">" + dateColor + "</a>"); if (this.isHoliday(String.valueOf(displayMonth), String.valueOf(displayDay), String.valueOf(displayYear))) { html.append(CalendarEvent.getIcon("holiday", contextPath) + "<font color=\"blue\"><br />"); } //get all events categories and respective counts. HashMap events = this.getEventList(String.valueOf(displayMonth), String.valueOf(displayDay), String.valueOf(displayYear)); if (events.size() > 0) { html.append( "<table width=\"12%\" align=\"center\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"dayIcon\">"); for (int i = 0; i < Array.getLength(CalendarEventList.EVENT_TYPES); i++) { String eventType = CalendarEventList.EVENT_TYPES[i]; if (events.containsKey(eventType)) { if (!eventType.equals(CalendarEventList.EVENT_TYPES[7])) { Object eventObj = events.get(eventType); // use reflection to call the size method on the event list object String eventSize = (String) ObjectUtils.getObject(eventObj, "sizeString"); if (!eventSize.equals("0")) { html.append("<tr><td>" + CalendarEvent.getIcon(eventType, contextPath) + "</td><td> " + eventSize + "</td></tr>"); } } } } html.append("</table>"); } //end of events display. } html.append("</td>"); if ((cellNo + 1) % 7 == 0) { html.append("</tr>"); } // end check for end of row } // end for-loop html.append("</table></td></tr>"); html.append("</table>"); //Display a link that selects today if (popup) { Calendar tmp = Calendar.getInstance(locale); tmp.set(Calendar.HOUR, 0); tmp.set(Calendar.MINUTE, 0); tmp.set(Calendar.SECOND, 0); tmp.set(Calendar.MILLISECOND, 0); if (timeZone != null) { tmp.setTimeZone(timeZone); } int displayMonth = tmp.get(Calendar.MONTH) + 1; int displayYear = tmp.get(Calendar.YEAR); int displayDay = tmp.get(Calendar.DAY_OF_MONTH); html.append("<p class=\"smallfooter\">Today: " + "<a href=\"javascript:returnDate(" + displayDay + ", " + displayMonth + ", " + displayYear + ");\"" + ">" + this.getToday() + "</p>"); html.append("<input type=\"hidden\" name=\"year\" value=\"" + cal.get(Calendar.YEAR) + "\">"); html.append("<input type=\"hidden\" name=\"month\" value=\"" + (cal.get(Calendar.MONTH) + 1) + "\">"); } html.append("<input type=\"hidden\" name=\"day\" value=\"" + (cal.get(Calendar.DATE)) + "\">"); return html.toString(); }
From source file:kx.c.java
/** * A helper function for nx, returns the number of elements in the supplied object. * e.g. for a Dict, the number of keys// w w w. j a v a 2 s . c o m * for a Flip, the number of rows * an array, the length of the array * * @param x Object to be serialized * * @return number of elements in an object. * * @throws UnsupportedEncodingException If the named charset is not supported */ public static int n(Object x) throws UnsupportedEncodingException { return x instanceof Dict ? n(((Dict) x).x) : x instanceof Flip ? n(((Flip) x).y[0]) : x instanceof char[] ? new String((char[]) x).getBytes(encoding).length : Array.getLength(x); }
From source file:ArrayUtils.java
/** * Reverses the order of an array. Similar to {@link #reverse(Object[])} but * works for primitive arrays as well.//from w ww . j a v a 2s . c o m * * @param array * The array to reverse * @return The reversed array, same as the original reference */ public static Object reverseP(Object array) { if (array == null) return array; if (array instanceof Object[]) return reverse((Object[]) array); Object temp; final int aLen = Array.getLength(array); for (int i = 0; i < aLen / 2; i++) { temp = Array.get(array, i); put(array, Array.get(array, aLen - i - 1), i); put(array, temp, aLen - i - 1); } return array; }
From source file:com.espertech.esper.client.scopetest.EPAssertionUtil.java
/** * For a given array, copy the array elements into a new array of Object[] type. * @param array input array//from w w w. j a va 2s .c o m * @return object array */ public static Object[] toObjectArray(Object array) { if ((array == null) || (!array.getClass().isArray())) { throw new IllegalArgumentException( "Object not an array but type '" + (array == null ? "null" : array.getClass()) + "'"); } int size = Array.getLength(array); Object[] val = new Object[size]; for (int i = 0; i < size; i++) { val[i] = Array.get(array, i); } return val; }
From source file:com.mawujun.util.ObjectUtils.java
/** * <p>Clone an object.</p>//from w ww .j ava2 s . co m * * @param <T> the type of the object * @param obj the object to clone, null returns null * @return the clone if the object implements {@link Cloneable} otherwise {@code null} * @throws CloneFailedException if the object is cloneable and the clone operation fails * @since 3.0 */ public static <T> T clone(final T obj) { if (obj instanceof Cloneable) { final Object result; if (obj.getClass().isArray()) { final Class<?> componentType = obj.getClass().getComponentType(); if (!componentType.isPrimitive()) { result = ((Object[]) obj).clone(); } else { int length = Array.getLength(obj); result = Array.newInstance(componentType, length); while (length-- > 0) { Array.set(result, length, Array.get(obj, length)); } } } else { try { final Method clone = obj.getClass().getMethod("clone"); result = clone.invoke(obj); } catch (final NoSuchMethodException e) { throw new CloneFailedException( "Cloneable type " + obj.getClass().getName() + " has no clone method", e); } catch (final IllegalAccessException e) { throw new CloneFailedException("Cannot clone Cloneable type " + obj.getClass().getName(), e); } catch (final InvocationTargetException e) { throw new CloneFailedException("Exception cloning Cloneable type " + obj.getClass().getName(), e.getCause()); } } @SuppressWarnings("unchecked") final T checked = (T) result; return checked; } return null; }