Home  >  Article  >  Java  >  How to define data types in Java

How to define data types in Java

WBOY
WBOYforward
2023-04-21 11:16:091587browse

1. Explanation

There are two reasons why new T() cannot be used in generic code. One is that the type cannot be determined due to erasure; but it cannot be determined whether T contains No-argument constructor.

We use the factory pattern generic method to create instance objects, create IntegerFactory factories, and create Integer instances. If the code changes later, a new factory type can be added.

2. Example

/**
 * 使用工厂方法来创建实例
 *
 * @param <T>
 */
interface Factory<T>{
    T create();
}
 
class Creater<T>{
    T instance;
    public <F extends Factory<T>> T newInstance(F f) {
     instance=f.create();
     return instance;
    }
}
 
class IntegerFactory implements Factory<Integer>{
    @Override
    public Integer create() {
     Integer integer=new Integer(9);
     return integer;
    }
}

The above is the detailed content of How to define data types in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete