How to pass a class as a parameter in another class and return a variable that is inside a Thread

1

I work with Delphi and decided to learn how to make java applications, and I came across a problem.

I have this class

    public class Dados {
    public void getJson(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Object retorno = null;
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpGet request       = new HttpGet();

                    request.setURI(new URI(url));

                    HttpResponse response = httpclient.execute(request);
                    InputStream content   = response.getEntity().getContent();
                    Reader reader         = new InputStreamReader(content);

                    Gson gson = new Gson();
                    retorno   = gson.fromJson(reader, HashMap.class);

                    content.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

The above class works, but I would like to do two more things in it. First I would like to pass a class (any class) as a parameter and then return what is in the "return" variable, for example:

 public class Dados {
    public Class<T> getJson(Class<T> classeTal, final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Object retorno = null;
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpGet request       = new HttpGet();

                    request.setURI(new URI(url));

                    HttpResponse response = httpclient.execute(request);
                    InputStream content   = response.getEntity().getContent();
                    Reader reader         = new InputStreamReader(content);

                    Gson gson = new Gson();
                    retorno   = gson.fromJson(reader, classeTal.class);

                    content.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    return retorno;
    }
}

Can anyone tell me how I would do this and if you can give me an example? Because the example I gave does not work.

    
asked by anonymous 14.08.2017 / 14:44

1 answer

0

I think you can try with generics, for example:

public class Dados<T> implements Runnable{
    @Override
    public void run() {
        T object = (T)new Object(); 
    }
}

public class App {
    public static void main(String[] args) {
        Dados dados = new Dados<String>();
    }
}
    
14.08.2017 / 18:30