This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Create instance of generic type in Java?
I got these classes
public abstract class Base {
public String Id = "originalId";
}
public class InstanceOfBase extends Base {
public void setString(String test) {
this.Id = test;
}
}
public class UseIt {
public Test<InstanceOfBase> test = new Test<InstanceOfBase>();
public void run() {
InstanceOfBase instanceOfBase = test.createMe();
System.out.println(instanceOfBase.Id);
}
}
public abstract class Test<E extends Base> {
public E createMe() {
// How do I do this?
return new E();
}
}
The code above does not compile because it does not know how to create E. how can I achieve this?
When I invoke the run method, I expect it should print "originalId".
Unfortunately you cannot create classes from generic types in java. But you can do as Justin Rudd suggested in this thread and write:
public E createMe(Class<E> clazz)
{
return clazz.newInstance();
}
So you use the class archetype to create a new instance. Invoking it could be:
InstanceOfBase instanceOfBase = test.createMe(test.getClass)
Related
This question already has answers here:
Call a method of subclass in Java
(7 answers)
Closed 2 years ago.
Have a below code snippet.
public class Character {
private static String type;
public void doMainSomething() {
System.out.println("Doing Main Something");
}
public static class Gorgon extends Character implements Monster {
public int level;
#Override
public int getLevel() { return level; }
public Gorgon() {
Character.type = "Gorgon";
}
public void doSomething() {
System.out.println("Doing Something");
}
}
public static void main(String[] args) {
Character.Gorgon gor = new Character.Gorgon();
Monster mon = new Character.Gorgon();
mon.doSomething(); -> Error
}
}
How can I access inner class's Gorgon method doSomething using mon ? Is there any specific way, so that we could access class's method using Interface's ref type ?
Proper way is to declare the doSomething() method on Monster interface. If a method needs to be called on interface type, then that method needs to be on the interface or it's parent.
If that is not doable, then you can safely cast the mon to Character.Gorgon
if (mon instanceof Character.Gorgon) {
((Character.Gorgon) mon).doSomething();
}
This question already has answers here:
What is the difference between dynamic and static polymorphism in Java?
(14 answers)
Closed 3 years ago.
Why method overloading called as static or compile-time polymorphism
sample in Java.
class StaticPolymorphismSample {
void polymorphicMethod(int a) {
}
void polymorphicMethod(int a, int b) {
}
void polymorphicMethod(String a) {
}
void nonPolymorphicMethod(int a) {
}
void nonPolymorphicMethod1(int a) {
}
}
so my question is.
Why we say that method overloading ( in this case polymorphicMethod methods ) are static polymorphism , but another methods( nonPolymorphicMethod(int a) nonPolymorphicMethod1(int a) ) are not polymorphism.
technically I cannot see different between method with same name and different parameters and method with different,
all answers in here and topics in google is not applicable for my question.
For nonPolymorphicMethod1(int a) the reason this wouldn't be considered polymorphic is because it has a different name from the other nonPolymorphicMethods.
For nonPolymorphicMethod( int a, int b ) and nonPolymorphicMethod( int a ) these aren't considered polymorphic as they don't take the same parameters. Edit This is Wrong See Next Line
The other methods you've shown are polymorphic due to their sharing of a name, but differing parameter types or number of parameters.
A better example of polymorphism in methods would be :
public abstract class ClassA
{
public Object getObject()
{
return new Object();
}
}
public class ClassB extends ClassA
{
#Override
public ClassB getObject()
{
return new ClassB();
}
}
public class ClassC extends ClassA
{
#Override
public ClassC getObject()
{
ClassC example = new ClassC();
example.doStuff();
return example;
}
private void doStuff()
{
// Do Something To Change The Object
}
}
This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 4 years ago.
I have this code:
public interface Interface1{
void interfaceMethod1();
}
public class Class1<T extends Class0&Interface1>{
private T field;
public T getField(){
return field;
}
}
When I invoke class1.getField().interfaceMethod1(), where class1 is Class1 instance, I see error "Cannot resolve method".
I want to define class with generic field which will include methods from Class0 and Interface1.
Assume we have next definitions:
public interface Interface1 {
void interfaceMethod1();
}
public class Class0 {
}
public class Class2 extends Class0 implements Interface1 {
#Override
public void interfaceMethod1() {
}
}
public class Class1<T extends Class0 & Interface1> {
private T field;
public T getField() {
return field;
}
}
When you have
Class1 class1 = new Class1();
class1.getField().interfaceMethod1();
it is called type erasure. It means all generic arguments assumed to be Object, so class1.getField() return Object which lack of interfaceMethod1 method.
To fix that you should do this:
Class1<Class2> class1 = new Class1<>();
class1.getField().interfaceMethod1();
Now everything compiles fine.
This question already has answers here:
how to inherit Constructor from super class to sub class
(6 answers)
Closed 7 years ago.
I have created an abstract base class BaseModelDao with three constructors. When I create a class SubscriberScoreDao that extends BaseModelDao I have to redefine all three constructors in the subclass in order to avoid compile time errors. Is there a way to take advantage of the constructors I have defined in my BaseModelDao without having to reimplement the same logic in every subclass?
BaseModelDao
public abstract class BaseModelDao<T extends Model> {
private static final String TAG = BaseModelDao.class.getSimpleName();
private List<T> mModelList;
protected BaseModelDao() {
mModelList = new ArrayList<>();
}
protected BaseModelDao(Response<T>[] responseArray) {
mModelList = fromResponseArray(responseArray);
}
protected BaseModelDao(Response<T> response) {
mModelList = fromResponse(response);
}
public List<T> getModelList() {
return mModelList;
}
public abstract Class<T> getModelClass();
private List<T> fromResponse(Response<T> response) {
List<T> responseList = response.getResultData();
return responseList;
}
public List<T> fromResponseArray(Response<T>[] responseArray) {
return fromResponse(getResponseObjectFromArray(responseArray));
}
// more helper methods...
}
SubscriberScoreDao
public class SubscriberScoreDao extends BaseModelDao<SubscriberScore> {
public static final String TAG = SubscriberScoreDao.class.getSimpleName();
public SubscriberScoreDao(){
super();
}
public SubscriberScoreDao(Response<SubscriberScore>[] responseArray) {
super(responseArray);
}
public SubscriberScoreDao(Response<SubscriberScore> responseArray) {
super(responseArray);
}
#Override
public Class<SubscriberScore> getModelClass() {
return SubscriberScore.class;
}
}
The constructors shown above are the ones I am trying to eliminate. When I want to use the SubscriberScoreDao in code it looks like this.
LendingRestClient.getInstance().getSubscriberScoring(new Callback<Response<SubscriberScore>[]>() {
#Override
public void success(Response<SubscriberScore>[] responseArray, retrofit.client.Response response) {
mSubscriberScoreDao = new SubscriberScoreDao(responseArray);
}
#Override
public void failure(RetrofitError error) {
}
});
If the three constructors that call super() are not defined in the SubscriberScoreDao then the code throws a compile time error at this line:
mSubscriberScoreDao = new SubscriberScoreDao(responseArray);
Error:
Is there a way to not define the constructors in every subclass and avoid this error?
You could declare the constructor (in the base class) with a vararg:
class Super<T> {
private List<T> responses;
public Super(Response<T>...responses) {
this.responses = Arrays.asList(responses);
}
}
Your subclass would only have to declare 1 constructor, which takes care of the functionality of all 3 of the constructors you have.
class Sub extends Super<SubscriberScore> {
public Sub(Response<SubscriberScore>...responses) {
super(responses);
}
}
You can now instantiate Sub as:
new Sub();
new Sub(new Response<SubscriberScore>());
new Sub(new Response<SubscriberScore>[] {
});
This question already has answers here:
Instantiating a generic class in Java [duplicate]
(10 answers)
Closed 8 years ago.
Here's the code:
package Fabrika.Trake;
import Vozila.*;
public class Traka<T extends Vozilo> extends Thread
{
protected int vrijemeRada;
...
#Override
public void run()
{
while(true)
{
//I want to create the object here
}
}
}
Now, let's say I have a class called Auto which extends Vozilo.
I'd like to know if there is a way of constructing an object of type T without using reflection. Something like:
T object = new T();
This, of course, is completely incorrect, but it just serves as an illustration of what I'd like to do. :)
Use a type token.
public class Traka<T extends Vozilo> extends Thread
{
private Class<T> type;
protected int vrijemeRada;
...
public Traka(Class<T> type) {
this.type = type;
}
#Override
public void run()
{
while(true)
{
//I want to create the object here
T object = type.newInstance();
}
}
}
This works - of course - only with constructors that have a known number of arguments. My example uses a no-arg constructor.
And: Do not extend Thread! Implement Runnable instead. And then uses those runnables, wherever you need them.
You can't do this with just the generic type T.
To create an instance you need a Class instance.
E.g.:
public class Traka<T extends Vozilo> extends Thread
{
protected int vrijemeRada;
...
private Class<T> type;
public Traka(Class<T> type) {
this.type = type;
}
#Override
public void run()
{
while(true)
{
T newInstance = type.newInstace(); // this uses the default constructor
}
}
}
Usage:
Traka<Auto> autoTraka = new Traka(Auto.class);
The problem is that the generic type information T is erased at runtime. Therefore you need a Class instance to represent the type at runtime.
There is a special pattern for this: pass Class instance to the constructor of Traka, store it in a private variable, and the use that class to instantiate new objects, like this:
public class Traka<T extends Vozilo> extends Thread {
private Class<T> theClass;
public Traka(Class<T> theClass) {
this.theClass = theClass;
}
...
#Override
public void run() {
while(true) {
T inst = theClass.newInstance();
}
}
}
Note: In case you were wondering why Class became parameterized in Java 5, the pattern above is the answer.