Java中有类似Objective-C类的东西吗?

时间:2015-10-17 21:07:21

标签: java objective-c-category

在Objective C中你可以创建Category类,在那里你可以'扩展'Apple Core Classes的功能。例如,UIColor类有无数的颜色,但是假设您想要一个特定的主题用于项目,您可以像这样简单地创建一个Category

@interface UIColor (CustomColors) 

+ (UIColor) myCustomColor;

@end

@implementation UIColor (CustomColors) 

+ (UIColor) myCustomColor {
    return [UIColor colorWithRed:...];
}

@end

Java中有类似的内容吗?

2 个答案:

答案 0 :(得分:1)

在Android(以及一般的Java)中,您必须使用子类来实现相同的结果。

E.g:

public class FlickrFetchr {
private static final String TAG="FlickerFetchr";
private static final String API_KEY="075a834f9703a704c763d335f";

 byte[] getUrlBytes(String urlSpec) throws IOException {
     URL url=new URL(urlSpec);
     HttpURLConnection connection=(HttpURLConnection)url.openConnection();

     try {
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         InputStream in = connection.getInputStream();

         if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK)
             return null;

         int bytesHead=0;
         byte[] buffer=new byte[1024];
         while((bytesHead=in.read(buffer))>0){
             out.write(buffer,0,bytesHead);
         }

         out.close();
         return out.toByteArray();

     }catch(Exception e){
         Log.e(TAG,"Read Exception ",e);
         return null;
     }finally{
         connection.disconnect();
     }
 }

public String getUrl(String urlSpec) throws IOException {
    return new String(getUrlBytes(urlSpec));
}

public void fetchItems(){
    try{
        String url= Uri.parse("https://api.flickr.com/services/rest/").buildUpon().appendQueryParameter("method","flickr.photos.getRecent")
                .appendQueryParameter("api_key",API_KEY)
                .appendQueryParameter("format","json")
                .appendQueryParameter("nojsoncallback","1")
                .appendQueryParameter("extras","url_s")
                .build().toString();
        String jsonString=getUrl(url);
        Log.i(TAG,"Received XML:"+ jsonString);
    }catch(Exception e){
        Log.e(TAG,"Failed to fetch",e);
    }
}

答案 1 :(得分:1)

Java 8为接口添加了默认实现,但在Android中还没有类别(iOS)或扩展(Swift)的想法。