java 常用工具类?

1:  设计一个方法要求检查一个指定字符是否允许作为 Java 标识符中的首字符,并测试?
2:  设计一个方法,接收一个字符和字符串,然后返回这个字符在这个字符串出现的次数,并测试?
3:  设计一个类并提供一个方法,将整型值转换为二进制、十六进制和八进制值?
4:  设计一个方法,接收一个byte然后将其转换字母并要求是大写的,再设计一个方法判断其是元音还是辅音。最后在main方法中声明一个数组,要求随机产生10个符合字母范围的数据放在数组内,并使用一个方法转成大写,另个方法判断其是元音还是辅音,并打印出来。


5:  设计一个方法,接收三个参数分别是年,月,日,然后返加一个Calender类型的对象,再设计一个方法接收Calender类型对象,在方法内分别打印此日期是一个月的第几天,一年的第几天,一周的第几天,此天是周几,这个月的第一天是周几,是一周的第几天。

回答: java 常用工具类?

  1. 这些方法很多都已经有了

    /*
     * Copyright 2005 Joe Walker
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    package org.directwebremoting.util;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.RandomAccessFile;
    import java.io.Reader;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.URLDecoder;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Locale;
    import java.util.Map;
    import java.util.Set;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.xml.transform.TransformerFactoryConfigurationError;
    
    /**
     * 一些通用的方法
     * Various utilities, mostly to make up for JDK 1.4 functionallity that is not
     * in JDK 1.3
     * @author Joe Walker [joe at getahead dot ltd dot uk]
     */
    public final class LocalUtil
    {
        /**
         * splitInbound() returns the type info in this parameter
         */
        public static final int INBOUND_INDEX_TYPE = 0;
    
        /**
         * splitInbound() returns the value info in this parameter
         */
        public static final int INBOUND_INDEX_VALUE = 1;
    
        /**
         * Prevent instansiation
         */
        private LocalUtil()
        {
        }
    
        /**
         * Replacement for String#replaceAll(String, String) in JDK 1.4+
         * @param text source text
         * @param repl the stuff to get rid of
         * @param with the stuff to replace it with
         * @return replaced text or null if any args are null
         */
        public static String replace(String text, String repl, String with)
        {
            if (text == null || repl == null || with == null || repl.length() == 0)
            {
                return text;
            }
    
            StringBuffer buf = new StringBuffer(text.length());
            int searchFrom = 0;
            while (true)
            {
                int foundAt = text.indexOf(repl, searchFrom);
                if (foundAt == -1)
                {
                    break;
                }
    
                buf.append(text.substring(searchFrom, foundAt)).append(with);
                searchFrom = foundAt + repl.length();
            }
            buf.append(text.substring(searchFrom));
    
            return buf.toString();
        }
    
        /**
         * 判断给定的字符串是否符合 Java 标识符的规范
         * 
         * Determines if the specified string is permissible as a Java identifier.
         * Returns true if the string is non-null, non-zero length with a Java
         * identifier start as the first character and Java identifier parts in all
         * remaining characters.
         * @param test the string to be tested.
         * @return true if the string is a Java identifier, false otherwise.
         * @see java.lang.Character#isJavaIdentifierPart(char)
         * @see java.lang.Character#isJavaIdentifierStart(char)
         */
        public static boolean isJavaIdentifier(String test)
        {
            if (test == null || test.length() == 0)
            {
                return false;
            }
    
            if (!Character.isJavaIdentifierStart(test.charAt(0)) && test.charAt(0) != '_')
            {
                return false;
            }
    
            for (int i = 1; i < test.length(); i++)
            {
                if (!Character.isJavaIdentifierPart(test.charAt(i)) && test.charAt(i) != '_')
                {
                    return false;
                }
            }
    
            return true;
        }
    
        /**
         * Determines if the specified string contains only Unicode letters or
         * digits as defined by [email protected] Character#isLetterOrDigit(char)}
         * @param test The string to test
         * @return true if the string is non-null, non-empty and contains only
         * characters that are unicode letters or digits
         * @see Character#isLetterOrDigit(char)
         */
        public static boolean isLetterOrDigitOrUnderline(String test)
        {
            if (test == null || test.length() == 0)
            {
                return false;
            }
    
            for (int i = 0; i < test.length(); i++)
            {
                if (!Character.isLetterOrDigit(test.charAt(i)) && test.charAt(i) != '_')
                {
                    return false;
                }
            }
    
            return true;
        }
    
        /**
         * True if c1 is java.lang.Boolean and c2 is boolean, etc.
         * @param c1 the first class to test
         * @param c2 the second class to test
         * @return true if the classes are equivalent
         */
        public static boolean isEquivalent(Class c1, Class c2)
        {
            if (c1 == Boolean.class || c1 == Boolean.TYPE)
            {
                return c2 == Boolean.class || c2 == Boolean.TYPE;
            }
            else if (c1 == Byte.class || c1 == Byte.TYPE)
            {
                return c2 == Byte.class || c2 == Byte.TYPE;
            }
            else if (c1 == Character.class || c1 == Character.TYPE)
            {
                return c2 == Character.class || c2 == Character.TYPE;
            }
            else if (c1 == Short.class || c1 == Short.TYPE)
            {
                return c2 == Short.class || c2 == Short.TYPE;
            }
            else if (c1 == Integer.class || c1 == Integer.TYPE)
            {
                return c2 == Integer.class || c2 == Integer.TYPE;
            }
            else if (c1 == Long.class || c1 == Long.TYPE)
            {
                return c2 == Long.class || c2 == Long.TYPE;
            }
            else if (c1 == Float.class || c1 == Float.TYPE)
            {
                return c2 == Float.class || c2 == Float.TYPE;
            }
            else if (c1 == Double.class || c1 == Double.TYPE)
            {
                return c2 == Double.class || c2 == Double.TYPE;
            }
            else if (c1 == Void.class || c1 == Void.TYPE)
            {
                return c2 == Void.class || c2 == Void.TYPE;
            }
    
            return false;
        }
    
        /**
         * @param type The class to de-primitivize
         * @return The non-privitive version of the class
         */
        public static Class getNonPrimitiveType(Class type)
        {
            if (!type.isPrimitive())
            {
                return type;
            }
            else if (type == Boolean.TYPE)
            {
                return Boolean.class;
            }
            else if (type == Byte.TYPE)
            {
                return Byte.class;
            }
            else if (type == Character.TYPE)
            {
                return Character.class;
            }
            else if (type == Short.TYPE)
            {
                return Short.class;
            }
            else if (type == Integer.TYPE)
            {
                return Integer.class;
            }
            else if (type == Long.TYPE)
            {
                return Long.class;
            }
            else if (type == Float.TYPE)
            {
                return Float.class;
            }
            else if (type == Double.TYPE)
            {
                return Double.class;
            }
            else if (type == Void.TYPE)
            {
                return Void.class;
            }
    
            return null;
        }
    
        /**
         * Add headers to prevent browers and proxies from caching this reply.
         * @param resp The response to add headers to
         */
        public static void addNoCacheHeaders(HttpServletResponse resp)
        {
            // Set standard HTTP/1.1 no-cache headers.
            resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    
            // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
            resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
    
            // Set standard HTTP/1.0 no-cache header.
            resp.setHeader("Pragma", "no-cache");
    
            // Set to expire far in the past. Prevents caching at the proxy server
            resp.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
        }
    
        /**
         * Is this class one that we auto fill, so the user can ignore?
         * @param paramType The type to test
         * @return true if the type is a Servlet type
         */
        public static boolean isServletClass(Class paramType)
        {
            return paramType == HttpServletRequest.class ||
                   paramType == HttpServletResponse.class ||
                   paramType == ServletConfig.class ||
                   paramType == ServletContext.class ||
                   paramType == HttpSession.class;
        }
    
        /**
         * URL decode a value. This method gets around the lack of a
         * decode(String, String) method in JDK 1.3.
         * @param value The string to decode
         * @return The decoded string
         */
        public static String decode(String value)
        {
            if (!testedDecoder)
            {
                try
                {
                    decode14 = URLDecoder.class.getMethod("decode", new Class[] { String.class, String.class });
                }
                catch (Exception ex)
                {
                    if (!warn13)
                    {
                        log.warn("URLDecoder.decode(String, String) is not available. Falling back to 1.3 variant.");
                        warn13 = true;
                    }
                }
    
                testedDecoder = true;
            }
    
            if (decode14 != null)
            {
                try
                {
                    return (String) decode14.invoke(null, new Object[] { value, "UTF-8" });
                }
                catch (Exception ex)
                {
                    log.warn("Failed to use JDK 1.4 decoder", ex);
                }
            }
    
            return URLDecoder.decode(value);
        }
    
        /**
         * 用反射给对象设置属性集
         * 
         * Set use reflection to set the setters on the object called by the keys
         * in the params map with the corresponding values
         * @param object The object to setup
         * @param params The settings to use
         * @param ignore List of keys to not warn about if they are not properties
         *               Note only the warning is skipped, we still try the setter
         */
        public static void setParams(Object object, Map params, List ignore)
        {
            for (Iterator it = params.entrySet().iterator(); it.hasNext();)
            {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                Object value = entry.getValue();
    
                try
                {
                    setProperty(object, key, value);
                }
                catch (NoSuchMethodException ex)
                {
                    if (ignore != null && !ignore.contains(key))
                    {
                        log.warn("No property '" + key + "' on " + object.getClass().getName());
                    }
                }
                catch (InvocationTargetException ex)
                {
                    log.warn("Error setting " + key + "=" + value + " on " + object.getClass().getName(), ex.getTargetException());
                }
                catch (Exception ex)
                {
                    log.warn("Error setting " + key + "=" + value + " on " + object.getClass().getName(), ex);
                }
            }
        }
    
        /**
         * 用反射给对象设置属性,通过给定的属性名。
         * 
         * Set a property on an object using reflection
         * @param object The object to call the setter on
         * @param key The name of the property to set.
         * @param value The new value to use for the property
         * @throws NoSuchMethodException Passed on from reflection code
         * @throws SecurityException Passed on from reflection code
         * @throws IllegalAccessException Passed on from reflection code
         * @throws IllegalArgumentException Passed on from reflection code
         * @throws InvocationTargetException Passed on from reflection code
         */
        public static void setProperty(Object object, String key, Object value) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
        {
            Class real = object.getClass();
    
            String setterName = "set" + key.substring(0, 1).toUpperCase(Locale.ENGLISH) + key.substring(1);
    
            try
            {
                // Can we work with whatever type we were given?
                Method method = real.getMethod(setterName, new Class[] { value.getClass() });
                method.invoke(object, new Object[] { value });
                return;
            }
            catch (NoSuchMethodException ex)
            {
                // If it is a string then next we try to coerce it to the right type
                // otherwise we give up.
                if (!(value instanceof String))
                {
                    throw ex;
                }
            }
    
            Method[] methods = real.getMethods();
            for (int i = 0; i < methods.length; i++)
            {
                Method setter = methods[i];
    
                if (setter.getName().equals(setterName) && setter.getParameterTypes().length == 1)
                {
                    Class propertyType = setter.getParameterTypes()[0];
                    try
                    {
                        Object param = LocalUtil.simpleConvert((String) value, propertyType);
                        setter.invoke(object, new Object[] { param });
                        return;
                    }
                    catch (IllegalArgumentException ex)
                    {
                        // The conversion failed - it was speculative anyway so we
                        // don't worry now
                    }
                }
            }
    
            throw new NoSuchMethodException("Failed to find a property called: " + key + " on " + object.getClass().getName());
        }
    
        /**
         * Can the type be used in a call to [email protected] #simpleConvert(String, Class)}?
         * @param paramType The type to test
         * @return true if the type is acceptable to simpleConvert()
         */
        public static boolean isTypeSimplyConvertable(Class paramType)
        {
            return paramType == String.class ||
                paramType == Integer.class ||
                paramType == Integer.TYPE ||
                paramType == Short.class ||
                paramType == Short.TYPE ||
                paramType == Byte.class ||
                paramType == Byte.TYPE ||
                paramType == Long.class ||
                paramType == Long.TYPE ||
                paramType == Float.class ||
                paramType == Float.TYPE ||
                paramType == Double.class ||
                paramType == Double.TYPE ||
                paramType == Character.class ||
                paramType == Character.TYPE ||
                paramType == Boolean.class ||
                paramType == Boolean.TYPE;
        }
    
        /**
         * A very simple conversion function for all the IoC style setup and
         * reflection that we are doing.
         * @param value The value to convert
         * @param paramType The type to convert to. Currently ony primitive types and
         * String are supported.
         * @return The converted object.
         */
        public static Object simpleConvert(String value, Class paramType)
        {
            if (paramType == String.class)
            {
                return value;
            }
    
            if (paramType == Character.class || paramType == Character.TYPE)
            {
                if (value.length() == 1)
                {
                    return new Character(value.charAt(0));
                }
                else
                {
                    throw new IllegalArgumentException("Can't more than one character in string - can't convert to char: '" + value + "'");
                }
            }
    
            String trimValue = value.trim();
    
            if (paramType == Boolean.class)
            {
                if (trimValue.length() == 0)
                {
                    return null;
                }
    
                return Boolean.valueOf(trimValue);
            }
    
            if (paramType == Boolean.TYPE)
            {
                return Boolean.valueOf(trimValue);
            }
    
            if (paramType == Integer.class)
            {
                if (trimValue.length() == 0)
                {
                    return null;
                }
    
                return Integer.valueOf(trimValue);
            }
    
            if (paramType == Integer.TYPE)
            {
                if (trimValue.length() == 0)
                {
                    return new Integer(0);
                }
    
                return Integer.valueOf(trimValue);
            }
    
            if (paramType == Short.class)
            {
                if (trimValue.length() == 0)
                {
                    return null;
                }
    
                return Short.valueOf(trimValue);
            }
    
            if (paramType == Short.TYPE)
            {
                if (trimValue.length() == 0)
                {
                    return new Short((short) 0);
                }
    
                return Short.valueOf(trimValue);
            }
    
            if (paramType == Byte.class)
            {
                if (trimValue.length() == 0)
                {
                    return null;
                }
    
                return Byte.valueOf(trimValue);
            }
    
            if (paramType == Byte.TYPE)
            {
                if (trimValue.length() == 0)
                {
                    return new Byte((byte) 0);
                }
    
                return Byte.valueOf(trimValue);
            }
    
            if (paramType == Long.class)
            {
                if (trimValue.length() == 0)
                {
                    return null;
                }
    
                return Long.valueOf(trimValue);
            }
    
            if (paramType == Long.TYPE)
            {
                if (trimValue.length() == 0)
                {
                    return new Long(0);
                }
    
                return Long.valueOf(trimValue);
            }
    
            if (paramType == Float.class)
            {
                if (trimValue.length() == 0)
                {
                    return null;
                }
    
                return Float.valueOf(trimValue);
            }
    
            if (paramType == Float.TYPE)
            {
                if (trimValue.length() == 0)
                {
                    return new Float(0);
                }
    
                return Float.valueOf(trimValue);
            }
    
            if (paramType == Double.class)
            {
                if (trimValue.length() == 0)
                {
                    return null;
                }
    
                return Double.valueOf(trimValue);
            }
    
            if (paramType == Double.TYPE)
            {
                if (trimValue.length() == 0)
                {
                    return new Double(0);
                }
    
                return Double.valueOf(trimValue);
            }
    
            throw new IllegalArgumentException("Unsupported conversion type: " + paramType.getName());
        }
    
        /**
         * 得到除去包名的类名。
         * 
         * Get the short class name (i.e. without the package part)
         * @param clazz the class to get the short name of
         * @return the class name of the class without the package name
         */
        public static String getShortClassName(Class clazz)
        {
            String className = clazz.getName();
    
            char[] chars = className.toCharArray();
            int lastDot = 0;
            for (int i = 0; i < chars.length; i++)
            {
                if (chars[i] == '.')
                {
                    lastDot = i + 1;
                }
                else if (chars[i] == '$')
                {
                    chars[i] = '.';
                }
            }
    
            // This might come up in scans for locale/charset issues. It's not an
            // issue since we are talking about chars.
            return new String(chars, lastDot, chars.length - lastDot);
        }
    
        /**
         * Is this object property one that we can use in a JSON style or do we need
         * to get fancy. i.e does it contain only letters and numbers with an
         * initial letter.
         * @param name The name to test for JSON compatibility
         * @return true if the name is simple
         */
        public static boolean isSimpleName(String name)
        {
            if (name.length() == 0)
            {
                return false;
            }
    
            if (JavascriptUtil.isReservedWord(name))
            {
                return false;
            }
    
            boolean isSimple = Character.isLetter(name.charAt(0));
            for (int i = 1; isSimple && i < name.length(); i++)
            {
                if (!Character.isLetterOrDigit(name.charAt(i)))
                {
                    isSimple = false;
                }
            }
    
            return isSimple;
        }
    
        /**
         * Utility to essentially do Class forName and allow configurable
         * Classloaders.
         * <p>The initial implementation makes use of the context classloader for
         * the current thread.
         * @param className The class to create
         * @return The class if it is safe or null otherwise.
         * @throws ClassNotFoundException If <code>className</code> is not valid
         */
        public static Class classForName(String className) throws ClassNotFoundException
        {
            // Class.forName(className);
            return Thread.currentThread().getContextClassLoader().loadClass(className);
        }
    
        /**
         * Calling methods using reflection is useful for graceful fallback - this
         * is a helper method to make this easy
         * @param object The object to use as 'this'
         * @param method The method to call, can be null in which case null is returned
         * @param params The parameters to pass to the reflection call
         * @return The results of calling method.invoke() or null
         * @throws IllegalStateException If anything goes wrong
         */
        public static Object invoke(Object object, Method method, Object[] params) throws IllegalStateException
        {
            Object reply = null;
            if (method != null)
            {
                try
                {
                    reply = method.invoke(object, params);
                }
                catch (InvocationTargetException ex)
                {
                    throw new IllegalStateException("InvocationTargetException calling " + method.getName() + ": " + ex.getTargetException().toString());
                }
                catch (Exception ex)
                {
                    throw new IllegalStateException("Reflection error calling " + method.getName() + ": " + ex.toString());
                }
            }
    
            return reply;
        }
    
        /**
         * Utility to essentially do Class forName with the assumption that the
         * environment expects failures for missing jar files and can carry on if
         * this process fails.
         * @param name The name for debugging purposes
         * @param className The class to create
         * @param impl The implementation class - what should className do?
         * @return The class if it is safe or null otherwise.
         */
        public static Class classForName(String name, String className, Class impl)
        {
            Class clazz;
    
            try
            {
                clazz = classForName(className);
            }
            catch (ClassNotFoundException ex)
            {
                // We expect this sometimes, hence debug
                log.debug("Skipping '" + name + "' due to ClassNotFoundException on " + className + ". Cause: " + ex.getMessage());
                return null;
            }
            catch (NoClassDefFoundError ex)
            {
                // We expect this sometimes, hence debug
                log.debug("Skipping '" + name + "' due to NoClassDefFoundError on " + className + ". Cause: " + ex.getMessage());
                return null;
            }
            catch (TransformerFactoryConfigurationError ex)
            {
                // We expect this sometimes, hence debug
                log.debug("Skipping '" + name + "' due to TransformerFactoryConfigurationError on " + className + ". Cause: " + ex.getMessage());
                log.debug("Maybe you need to add xalan.jar to your webserver?");
                return null;
            }
    
            // Check it is of the right type
            if (!impl.isAssignableFrom(clazz))
            {
                log.error("Class '" + clazz.getName() + "' does not implement '" + impl.getName() + "'.");
                return null;
            }
    
            // Check we can create it
            try
            {
                clazz.newInstance();
            }
            catch (InstantiationException ex)
            {
                log.error("InstantiationException for '" + name + "' failed:", ex);
                return null;
            }
            catch (IllegalAccessException ex)
            {
                log.error("IllegalAccessException for '" + name + "' failed:", ex);
                return null;
            }
            catch (NoClassDefFoundError ex)
            {
                // We expect this sometimes, hence debug
                log.debug("Skipping '" + name + "' due to NoClassDefFoundError on " + className + ". Cause: " + ex.getMessage());
                return null;
            }
            catch (TransformerFactoryConfigurationError ex)
            {
                // We expect this sometimes, hence debug
                log.debug("Skipping '" + name + "' due to TransformerFactoryConfigurationError on " + className + ". Cause: " + ex.getMessage());
                log.debug("Maybe you need to add xalan.jar to your webserver?");
                return null;
            }
            catch (Exception ex)
            {
                // For some reason we can't catch this?
                if (ex instanceof ClassNotFoundException)
                {
                    // We expect this sometimes, hence debug
                    log.debug("Skipping '" + name + "' due to ClassNotFoundException on " + className + ". Cause: " + ex.getMessage());
                    return null;
                }
                else
                {
                    log.error("Failed to load '" + name + "' (" + className + ")", ex);
                    return null;
                }
            }
    
            return clazz;
        }
    
        /**
         * Utility to essentially do Class forName and newInstance with the
         * assumption that the environment expects failures for missing jar files
         * and can carry on if this process fails.
         * @param name The name for debugging purposes
         * @param className The class to create
         * @param impl The implementation class - what should className do?
         * @return The new instance if it is safe or null otherwise.
         */
        public static Object classNewInstance(String name, String className, Class impl)
        {
            Class clazz;
    
            try
            {
                clazz = LocalUtil.classForName(className);
            }
            catch (ClassNotFoundException ex)
            {
                // We expect this sometimes, hence debug
                log.debug("Skipping '" + name + "' due to ClassNotFoundException on " + className + ". Cause: " + ex.getMessage());
                return null;
            }
            catch (NoClassDefFoundError ex)
            {
                // We expect this sometimes, hence debug
                log.debug("Skipping '" + name + "' due to NoClassDefFoundError on " + className + ". Cause: " + ex.getMessage());
                return null;
            }
            catch (TransformerFactoryConfigurationError ex)
            {
                // We expect this sometimes, hence debug
                log.debug("Skipping '" + name + "' due to TransformerFactoryConfigurationError on " + className + ". Cause: " + ex.getMessage());
                return null;
            }
    
            // Check it is of the right type
            if (!impl.isAssignableFrom(clazz))
            {
                log.error("Class '" + clazz.getName() + "' does not implement '" + impl.getName() + "'.");
                return null;
            }
    
            // Check we can create it
            try
            {
                return clazz.newInstance();
            }
            catch (InstantiationException ex)
            {
                log.error("InstantiationException for '" + name + "' failed:", ex);
                return null;
            }
            catch (IllegalAccessException ex)
            {
                log.error("IllegalAccessException for '" + name + "' failed:", ex);
                return null;
            }
            catch (TransformerFactoryConfigurationError ex)
            {
                log.error("TransformerFactoryConfigurationError for '" + name + "' failed:", ex);
                return null;
            }
            catch (Exception ex)
            {
                log.error("Failed to load creator '" + name + "', classname=" + className + ": ", ex);
                return null;
            }
        }
    
        /**
         * InputStream closer that can cope if the input stream is null.
         * If anything goes wrong, the errors are logged and ignored.
         * @param in The resource to close
         */
        public static void close(InputStream in)
        {
            if (in == null)
            {
                return;
            }
    
            try
            {
                in.close();
            }
            catch (IOException ex)
            {
                log.warn(ex.getMessage(), ex);
            }
        }
    
        /**
         * InputStream closer that can cope if the input stream is null.
         * If anything goes wrong, the errors are logged and ignored.
         * @param in The resource to close
         */
        public static void close(Reader in)
        {
            if (in == null)
            {
                return;
            }
    
            try
            {
                in.close();
            }
            catch (IOException ex)
            {
                log.warn(ex.getMessage(), ex);
            }
        }
    
        /**
         * InputStream closer that can cope if the input stream is null.
         * If anything goes wrong, the errors are logged and ignored.
         * @param in The resource to close
         */
        public static void close(RandomAccessFile in)
        {
            if (in == null)
            {
                return;
            }
    
            try
            {
                in.close();
            }
            catch (IOException ex)
            {
                log.warn(ex.getMessage(), ex);
            }
        }
    
        /**
         * Return a List of superclasses for the given class.
         * @param clazz the class to look up
         * @return the List of superclasses in order going up from this one
         */
        public static List getAllSuperclasses(Class clazz)
        {
            List classes = new ArrayList();
    
            Class superclass = clazz.getSuperclass();
            while (superclass != null)
            {
                classes.add(superclass);
                superclass = superclass.getSuperclass();
            }
    
            return classes;
        }
    
        /**
         * Return a list of all fields (whatever access status, and on whatever
         * superclass they were defined) that can be found on this class.
         * <p>This is like a union of [email protected] Class#getDeclaredFields()} which
         * ignores and superclasses, and [email protected] Class#getFields()} which ignored
         * non-pubic fields
         * @param clazz The class to introspect
         * @return The complete list of fields
         */
        public static Field[] getAllFields(Class clazz)
        {
            List classes = getAllSuperclasses(clazz);
            classes.add(clazz);
            return getAllFields(classes);
        }
    
        /**
         * As [email protected] #getAllFields(Class)} but acts on a list of [email protected] Class}s and
         * uses only [email protected] Class#getDeclaredFields()}.
         * @param classes The list of classes to reflect on
         * @return The complete list of fields
         */
        private static Field[] getAllFields(List classes)
        {
            Set fields = new HashSet();
            for (Iterator it = classes.iterator(); it.hasNext();)
            {
                Class clazz = (Class) it.next();
                fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            }
    
            return (Field[]) fields.toArray(new Field[fields.size()]);
        }
    
        /**
         * The log stream
         */
        private static final Logger log = Logger.getLogger(LocalUtil.class);
    
        /**
         * Have we given a warning about URLDecoder.decode() in jdk 1.3
         */
        private static boolean warn13 = false;
    
        /**
         * Have we tested for the correct URLDecoder.decode()
         */
        private static boolean testedDecoder = false;
    
        /**
         * Are we using the jdk 1.4 version of URLDecoder.decode()
         */
        private static Method decode14 = null;
    }
    
    
    

有无建模工具能直接将数据库中的表转化成java中的类?

  1. Q
    有无建模工具能直接将数据库中的表转化成java中的类?

    只知道有个hibernate可将表直接转化为类,但我要在建模中先有类图,rose和pd如何做到?
  2. A
    PowerDesigner12完全支持hibernate以及JDO. 如果你事先生成了CDM或者PDM,那么请先从CDM/PDM自动生成OOM, 再OOM视图上,选择菜单Model -> Extended Model Definitions, 然后点击“Import an Extended Model Definitions”按钮,从中选择 Hibernate / JDO / JSF等等就可以了。这样你就可以从OOM自动生成Hibernate的代码了。非常简单。

定义一个读取常量的工具类(希望能帮我改进一下)

  1. Q
    有一个常量类,如下:
    public class Constants {
        public static final String AA = "aa";    
        public static final String BB = "bb";      
        public static final String CC = "cc";  
    }


    现在要写一个读取常量的工具类,我实现的写法如下:
    import java.lang.reflect.Field;
    import Constants;
    public class ConstantsUtil {
        public static String get(String key){
            Constants c=new Constants();
            Field[] fields = c.getClass().getDeclaredFields();
            for(int i=0;i<fields.length;i++){
                String varName = fields[i].getName();
                if(varName.equals(key)){
                    try {
                        Object o = fields[i].get(c);
                        return o.toString();
                    } catch (Exception e){  
                    }
                }
            }
            return null;
        }
    }

    但是感觉get()方法执行过程中先创建一个Constants的对象似乎很没必要,但是对反射不是很了解,问该怎么修改

    问题补充:苹果超人 写道
        import java.lang.reflect.Field;  
        import Constants;  
        public class ConstantsUtil {  
            public static String get(String key){  
                Field[] fields = Constants.class.getDeclaredFields();  
                for(int i=0;i<fields.length;i++){  
                    String varName = fields[i].getName();  
                    if(varName.equals(key)){  
                        try {  
                            Object o = fields[i].get(c);  
                            return o.toString();  
                        } catch (Exception e){    
                        }  
                    }  
                }  
                return null;  
            }  
        }  
    

    没有必要new,你说的很对。其实有三种方法获得class,下面是具的列子:
    //Use the class literal
    	Class string=java.lang.String.class;
    //Call the forName() static method of java.lang.Class
    	Class string=Class.forName("java.lang.String");
    //Call the getClass() method of an object
    	Class string="a String object".getClass();
    
    

    可是如果不new的话,
    Object o = fields[i].get(c); 
    该怎么换一种写法实现一样的功能呢?这里的get()方法需要传一个对象进去啊
  2. A
    引用可是如果不new的话,Java代码 
    Object o = fields[i].get(c);  

    Object o = fields[i].get(c); 该怎么换一种写法实现一样的功能呢?这里的get()方法需要传一个对象进去啊


    一开始直接用getFields 然后get就好
    get(object)这个方法如果你field定义是static,正如你写的AA BB CC都是static final,
    object就忽略,直接写null
    -------------------代码------------------------------

    Field[] fields = Constants.class.getFields();          
    String o =null;

    for(int i=0;i<fields.length;i++){    
    String varName = fields[i].getName();

         if(varName.equals(key)){                 
            try {
               o = fields[i].get(null).toString(); } catch (Exception e) {
    e.printStackTrace();
    }
           }
        }
    return o;         
    }

android工程中导入其他的jar包资源,为什么jar包内的工具类不可用?

  1. Q
    我现在写了provider工具包,促使输入的中文字符转换为英文,类似于英文词典集,现在要把这个jar包导入到android工程内,可是编译通过了,当点击按钮促使中文字符开始转译时,立刻就报出05-13 09:46:30.958: ERROR/AndroidRuntime(544): java.lang.NoClassDefFoundError: com.transcation.transUtils,请问,在android中导入其他资源jar包时是不是需要有其他的操作?
    问题补充:我的provider工具包是已经在java 标准工程中试验过了,是可以使用的,只是提供了一些静态属性和查询遍历方法,象这种工具类型的jar包是不是在android中还要有特别的东西进行标记,或者在SDK中标识什么的?
    问题补充:这个问题已经解决了:
        主要是因为我在导包的时候不应该给我的lib库添加library,应该是直接把jar文件倒进去,这样虽然在编译器上报出warning,但是在linux上编译是通过的,感谢你的回答,谢谢
  2. A
    编写provider工具包也要在android工程中写 ,这样可以确保没引用其他的类,
    有些jdk中的类在android标准包中是没有的..
    所以可能是这个原因..
    你把工具类的整个源码考到android工程中看看可有错误提示就知道了

Java开发工具eclipse窗口调试

  1. Q
         由于小子我自己操作不当,这个eclipse的窗口操作失败了。我不知道如何从第二张图片显示的窗口还原到第一幅图片所显示的窗口!请教各位大牛前辈和小伙伴们,能给给我指导一下,谢谢。

         若那位亲能够给我推荐一些学习Java基础知识的资料那就更加万分感谢了,哈哈。

          图片一
    Java开发工具eclipse窗口调试


          图片二:我Java开发工具eclipse现在的窗口模式
    Java开发工具eclipse窗口调试


          在最后附上一首我喜欢的诗,这首诗在小学学习时,当时一直不懂。呵呵

    嫦娥

    (唐)李商隐

    云母屏风烛影深,长河渐落晓星沉。


    嫦娥应悔偷灵药,碧海青天夜夜心。





  2. A
    双击类文件顶部标题即可。Java开发工具eclipse窗口调试
    这个地方,鼠标左键双击

java.sql.Connection类中有个方法

  1. Q
    java.sql.Connection类中有个方法

    PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException

    这个方法中参数的第二个作用是什么,代表什么意思?

    下面是org.springframework.jdbc.core.PreparedStatementCreatorFactory中的一段代码
    [code=java]

    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = null;
            if (generatedKeysColumnNames != null || returnGeneratedKeys) {
                    try {
                            if (generatedKeysColumnNames != null) {
                                    ps = con.prepareStatement(this.actualSql, generatedKeysColumnNames);   // TODO
                            }else {
                                    ps = con.prepareStatement(this.actualSql, PreparedStatement.RETURN_GENERATED_KEYS);
                            }
                    }catch (AbstractMethodError ex) {
                            throw new InvalidDataAccessResourceUsageException(
                                            "The JDBC driver is not compliant to JDBC 3.0 and thus " +
                                            "does not support retrieval of auto-generated keys", ex);
                }
            }
            else if (resultSetType == ResultSet.TYPE_FORWARD_ONLY && !updatableResults) {
                    ps = con.prepareStatement(this.actualSql);
            }
            else {
                    ps = con.prepareStatement(this.actualSql, resultSetType,
                                    updatableResults ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY);
            }
            setValues(ps);
            return ps;
    }



    呵呵,这个问题困惑我许久了!
    问题补充
    kimmking 写道finallygo 写道ms在联合主键的时候用
    jdbc规范里,insert时,获取自动添加的keys用的。
    但是翻了下mysql 5.1.13 驱动的实现
    第二个参数传 什么都可以,只要length > 0就可以。

    /**
    * @see Connection#prepareStatement(String, String[])
    */
    public java.sql.PreparedStatement prepareStatement(String sql,
    String[] autoGenKeyColNames) throws SQLException {
    java.sql.PreparedStatement pStmt = prepareStatement(sql);

    ((com.mysql.jdbc.PreparedStatement) pStmt)
    .setRetrieveGeneratedKeys((autoGenKeyColNames != null)
    && (autoGenKeyColNames.length > 0));

    return pStmt;
    }

    我说为啥,传什么都可以运行的通,呵呵,API说的不是很明白!
  2. A
    finallygo 写道ms在联合主键的时候用
    jdbc规范里,insert时,获取自动添加的keys用的。
    但是翻了下mysql 5.1.13 驱动的实现
    第二个参数传 什么都可以,只要length > 0就可以。

    /**
    * @see Connection#prepareStatement(String, String[])
    */
    public java.sql.PreparedStatement prepareStatement(String sql,
    String[] autoGenKeyColNames) throws SQLException {
    java.sql.PreparedStatement pStmt = prepareStatement(sql);

    ((com.mysql.jdbc.PreparedStatement) pStmt)
    .setRetrieveGeneratedKeys((autoGenKeyColNames != null)
    && (autoGenKeyColNames.length > 0));

    return pStmt;
    }

java 用File 类访问 linux unix "~/DS/abc" 路径的问题 关键是带~ 的就访问不到

  1. Q
    java 用File 类访问 linux unix   "~/DS/abc" 路径的问题  关键是带  ~ 的路径就访问不到

    请教大家如何处理呀  ,急等呀
    问题补充:Anddy 写道linux是通过一个~字符来引用自己的主目录。
    =============================
    在shell编程中用~来替换/home/用户名/目录,所以~用于在shell编程中。

    而在java中通过如下方法获取用户的主目录:
    String curDir = System.getProperty(”user.dir”);

    或者
    File dir = new File (”.”);
    
    System.out.println (”Current dir : ” + dir.getCanonicalPath());
    

    不是通过  user.dir  而是通过  user.home 来获取 '~'符号对应的用户根目录~然后替换~符号即可
  2. A
    linux是通过一个~字符来引用自己的主目录。
    =============================
    在shell编程中用~来替换/home/用户名/目录,所以~用于在shell编程中。

    而在java中通过如下方法获取用户的主目录:
    String curDir = System.getProperty(”user.dir”);

    或者
    File dir = new File (”.”);
    
    System.out.println (”Current dir : ” + dir.getCanonicalPath());
    

java中string类concat方法和+的区别

  1. Q
    请问java中string类concat方法和+的区别
  2. A

    都可以将2个字符串拼接到一块,这一点2这功能相同。

    但是 + 还可以将 字符串与非字符串(比如数字),拼接在一起,成为字符串。

木木的常用软件点评(2)------VC程序员常用工具篇

  1. Q
     过年了,事情可以暂时放一下了。总结一下很有必要。又看到外面饭馆写着“岁末收工,初六开炉“了。好了,废话不多说,接着上篇继续评点程序员常用工具。当然还得请朋友们留言,好做继续的整理和补充,谢谢!顺祝大家新年好!

    1.  IDE:钟情于VC++6.0,但是也感觉Visual Studio2008和2010的强大,可能迟早得转到VS高版本上来。在安装VC++6.0的时候记得安装sp6补丁和msdn(MSDN_1.5_精简安装版 )

    2. 辅助:Visual Assist,喜欢它代码自动补全,快速注释,头文件源文件切换:VC_VA_X_1561(最适合VC6) 

    WndTabs:很实用的添加标签功能,蛮喜欢

    3. 程序编辑器:notepad++,editplus。UltraEdit文本编辑器,Source Insight,codeblocks,自己钟情于notepad++和codeblocks,代码高亮做的蛮好

    4. 内存泄露检查:BoundsChecker 6.5 和Vld 

    5. 代码格式化和导出html:code2html 和CoolFormat

    6. 代码管家: 陈灯可重用代码段管理器,CodeHelp ,codelibray 

    7. 版本控制:TortoiseSVN 

    8. 注释:Doxygen 

    9. 日志:log4cpp 

    10. 打包: Inno Setup,http://www.innoide.org/  NSIS,setupfactory

    11. 加密狗:圣天狗

    12. 流程图:viso 2007和edraw

    13. 反编译:IDAPro ollydbg 和eXeScope 

    14. 串口调试:sscom32

    当然还得请朋友们留言,好做继续的整理和补充,谢谢!顺祝大家新年好!
    博客里面提供每个工具的超链接地址,欢迎点击
  2. A
    比较文件用的是 windiff,没什么优点,优点是自带的,基本装了vs的电脑都有。

系统的工具类是要设计成为单列类还是将所有的方法设计为静态方法?

  1. Q
    如题,恳请指出为什么。。。。。
  2. A
    系统的工具类一般这样设置
    建立一个private的无参构造函数,这样做的目的,是为了防止生成工具类的实例,也就是不能new一个工具类了
    如果是工具类中要对外公开的,也就是外部使用的方法,就设置成 public static得,这样使用的时候就可以直接使用了
    一般不需要单例
    这样说明白了吗?