Java通用对象初始化 [英] Java Generic object initialization

查看:135
本文介绍了Java通用对象初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先请看这段代码:

  public MultiThreadManager(Class< T> c){
T [ ] allJobs =(T [])Array.newInstance(c,MAX_THREAD_SIZE);
for(int i = 0; i< MAX_THREAD_SIZE; i ++){
allJobs [i] =(T)new Object();
service.submit(allJobs [i]);
getWaitingThreads()。add(allJobs [i]);


$ / code $ / pre

这是一个例外:

 线程main中的异常java.lang.ClassCastException:java.lang.Object不能转换为slave.JobTemplate 

$ p
$ b

MultiThreadManager的构造函数应该使用实现Callable的泛型类型(比如Job.java)。创建所有这些通用数据类型(Job,Java)的数组。初始化它,以便通用数据类型(Job.java)的构造函数将运行并在执行程序服务中执行它们。



请帮助我确定我的错误或请建议更好的方法。



预先感谢您

>

谢谢大家,但情况有点复杂:
Herez其他信息:

  public class Job扩展JobTemplate< String> {... details ...} 
公共抽象类JobTemplate< T>实施Callable< T> {... details ..}

最后

  MultiThreadManager<工作> threadManager = new MultiThreadManager< Job>(Job.class); 

再次感谢:)

解决方案

您需要更多的反思,就像您需要创建数组一样:

  allJobs [ i] = c.newInstance(); 

并用try-catch包围所有那些讨厌的检查异常。



但是,我建议使用新的Callable [] ,因为不需要进入实际工作类型的细节。你还应该考虑一种不需要反射的设计:调用者实例化作业而不是传入类对象。目前的解决方案受限于Job类型的限制,只能通过默认的构造函数实例化。


Please look at this snippet first :

public MultiThreadManager( Class<T> c) {
    T[] allJobs = (T[]) Array.newInstance( c , MAX_THREAD_SIZE ) ;
    for ( int i = 0 ; i < MAX_THREAD_SIZE ; i ++ ) {
        allJobs[i] = (T) new Object();
        service.submit( allJobs[i] );
        getWaitingThreads().add( allJobs[i] );
    }           
}

Here is the exception :

Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to slave.JobTemplate

What I am trying to do :

The Constructor of MultiThreadManager should take a generic type ( say Job.java ) which implements Callable. Create array of all those generic data type ( Job,java ) . Initialize it so the constructor of generic data type ( Job.java ) will run and execute them in a executor service.

Please help me identify my error or please suggest a better way.

Thank You in advance

Thanks you all , but things are little more complex : Herez the other information :

public class Job extends JobTemplate<String> {...details ...}
public abstract class JobTemplate< T > implements Callable<T> {...details..}

and finally

MultiThreadManager< Job > threadManager = new MultiThreadManager< Job >( Job.class );

Again thanks :)

解决方案

You'll need more reflection, just as you need to create the array:

allJobs[i] = c.newInstance();

and surround with try-catch for all those pesky checked exceptions.

However, I would suggest using new Callable[] because there's no need to go into the specifics of the actual job type. You should also consider a design where reflection is unnecessary: the caller instantiates the jobs instead of passing in the class object. The current solution suffers from the restriction on the Job type to be instantiated only through the default constructor.

这篇关于Java通用对象初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆