Utility Classes in Java Programming

北慕城南 提交于 2019-12-09 13:58:03

问题


I am new to Java and I referred regarding my question on the Net but not quite Satisfied. I want to know what the "Utility Class" in Java is?

Can anybody please tell me with an Example.

Thanks, david


回答1:


It's usually a class which only has static methods (possibly with a private constructor and marked abstract/final to prevent instantiation/subclassing). It only exists to make other classes easier to use - for example, providing a bunch of static methods to work with String values, performing extra actions which String itself doesn't support.

Utility classes generally don't operate on classes you have control over, as otherwise you'd usually put the behaviour directly within that class. They're not terribly neat in OO terms, but can still be jolly useful.




回答2:


To extends Jon Skeet's answer, java.lang.Math, java.util.Collections and java.util.Arrays are typical examples for such classes.




回答3:


There's a utility package, java.util, that contains a bunch of stuff like dates, times, string tokenizers... Not sure if that's what you're talking about.




回答4:


Its a class with all static methods and no member elements.




回答5:


public class Utils {

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

public static void unlockScreenOrientation(Activity activity) {
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}

public static void lockScreenOrientation(Activity activity) {
    int currentOrientation = activity.getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_PORTRAIT)
    {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    else
    {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}
// Get Http Post response
@Nullable
public static String getHttpResponse(String url, List<NameValuePair> nameValuePairs) {
    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(url);
    UrlEncodedFormEntity entity;
    try {
        entity = new UrlEncodedFormEntity(nameValuePairs);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);

        HttpEntity resEntity = response.getEntity();
        String res =  EntityUtils.toString(resEntity);
        return res;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

public static void CopyStream(InputStream is, OutputStream os) {
    final int buffer_size=1024;
    try
    {
        byte[] bytes=new byte[buffer_size];
        for(;;)
        {
            int count=is.read(bytes, 0, buffer_size);
            if(count==-1)
                break;
            os.write(bytes, 0, count);
        }
    }
    catch(Exception ex){}
}

public static JSONObject getJsonObjectFromXmlResponse(String xmlString) {
    JSONObject objectJson = new JSONObject();
    //JSONArray arrayJson = new JSONArray();

    XmlPullParser parser = Xml.newPullParser();
    try {
        parser.setInput(new StringReader(xmlString));
        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String name;
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("string")) {
                        String yourValue = parser.nextText();
                        //arrayJson = new JSONArray(yourValue);
                        objectJson = new JSONObject(yourValue);
                    }
                    break;
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return objectJson;
}

}



来源:https://stackoverflow.com/questions/3921387/utility-classes-in-java-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!