how can we Create instance for generic type in java

0 votes

Is it possible to create an instance of a generic type in Java? I think it is not possible sill want to know if it is possible

class BetaContainer<E>
{
    E createContents()
    {
        return what???
    }
}
Jun 7, 2018 in Java by sharth
• 3,370 points
5,703 views

2 answers to this question.

0 votes

You can with a classloader and the class name, eventually with some parameters shown in the code below

final ClassLoader classL = ...
final Class<?> aClass = classL.loadClass("java.lang.Integer");
final Constructor<?> constr= aClass.getConstructor(int.class);
final Object obj = constr.newInstance(123);
System.out.println("o = " + obj);
answered Jun 7, 2018 by Daisy
• 8,090 points
0 votes
private static class SomeContainer<E> {
    E createContents(Class<E> clazz) {
        return clazz.newInstance();
    }
}
answered Aug 27, 2018 by Sushmita
• 6,890 points

Related Questions In Java

0 votes
2 answers

How can I create File and write data in it using Java?

import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFiles{ ...READ MORE

answered Jul 26, 2018 in Java by samarth295
• 2,190 points
183 views
0 votes
1 answer

I am learning looping statements. Can you tell me how 'for-each' works in Java?

While programming we often write code that ...READ MORE

answered Apr 17, 2018 in Java by Rishabh
• 3,580 points
102 views
0 votes
1 answer

How can we get file extension in Java?

To get the file extension, we can ...READ MORE

answered May 8, 2018 in Java by Parth
• 4,640 points
608 views
0 votes
2 answers

How can we remove an element from an array in Java?

You can use ArrayUtils class remove method which ...READ MORE

answered May 24, 2018 in Java by UshaK
287 views
0 votes
1 answer

How can I make the return type of a method generic?

First of all, define callFriend: public <T extends ...READ MORE

answered May 18, 2018 in Java by sharth
• 3,370 points
53 views
0 votes
2 answers

How can I invoke a method when the method name is in the form of a given string?

You could probably use method invocation from reflection: Class<?> ...READ MORE

answered Aug 19, 2019 in Java by Sirajul
• 50,440 points
127 views
0 votes
2 answers

How do i create generic array in Java

as first tip you cannot assign value ...READ MORE

answered Feb 12 in Java by sama
6,156 views
0 votes
1 answer

How to calculate method execution time in Java ?

Use the following code : new Timer(""){{ ...READ MORE

answered May 24, 2018 in Java by Rishabh
• 3,580 points
295 views
0 votes
4 answers

How can we define global variables in java?

class G { static String globalVar ...READ MORE

answered Jan 29, 2019 in Java by zemiak
12,341 views
0 votes
4 answers

How can we compare dates in java?

public static String daysBetween(String day1, String day2) ...READ MORE

answered Sep 5, 2018 in Java by Sushmita
• 6,890 points
78 views