Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7642583
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T09:13:35+00:00 2026-05-31T09:13:35+00:00

Consider the following code: // … public class BaseClass { public BaseClass (int theParam)

  • 0

Consider the following code:

// ...
public class BaseClass
{
    public BaseClass (int theParam)
    {
        // ...whatever...
    }
}
public class DerivedType
{
    // ...Content does not matter...    
}


// ...elsewhere:

public <ElemType extends BaseClass> boolean doIt (ArrayList<ElemType> target)
{
    ElemType newElem=new ElemType (5) ; // "Cannot instantiate this type"

    // ...other code does not matter...

    return true ;
}

// ..

How can I create an instance of type ElemType in doIt?

The construct shown yields the error indicated.

ElemType.newInstance does not exist, which surprises me.

I’ve read practically all FAQs, answers and googleable material, but I cannot find anything helpful.

EDIT:
Yes I know reflection has its downsides, and is not the ultimate solution, for numerous reasons. The question is not “should I do it”, but “how would I do it”.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T09:13:36+00:00Added an answer on May 31, 2026 at 9:13 am

    As mentioned, type erasure of generic types does not allow that. But you can achieve what you want like this:

    public class BaseClass {
    
      public BaseClass(int theParam) {
        // ...whatever...
      }
      public BaseClass() {  
      }          
    }
    
    public class DerivedType extends BaseClass {
    }
    

    And now doIt() method gets the class argument for reference:

    public <D extends BaseClass> boolean doIt (ArrayList<D> target, Class<D> c)
    {
        try {
            D newElem = c.getDeclaredConstructor(int.class).newInstance(5);
        } catch (Exception e) {}
    
        // ...other code does not matter...
    
        return true ;
    }
    

    And you should call it like this:

        ArrayList<DerivedType> testList = new ArrayList<DerivedType>();
        testList.add(new DerivedType());
        testList.add(new DerivedType());
        doIt(testList, DerivedType.class);
    

    Hope that helps 🙂

    Note that, one may really want to be hacky and get rid of the class parameter and try this:

     public static <D extends BaseClass> boolean doIt (ArrayList<D> target)
     {
        try {
            D newElem1 =  ((Class<D>) ((ParameterizedType) target.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).getDeclaredConstructor(int.class).newInstance(5);
    
        } catch (Exception e) { e.printStackTrace();}
    
        return true ;
        }
    }
    

    In fact I thought so before the second edit 🙂 But this gets a “java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class” exception as you mention (I didn’t see it because of an overlooked catch statement). In short, Java runtime system does not store the parameterized types (in favor of backwards compatibility; so this may change in the future).

    So, it looks like it is not possible without ‘touching’ some class.

    However, other than the mentioned methods, I can think of two more things. First, if both the BaseClass and the DerivedType ‘D’ class implement clone() method, you can get a clone of an object from the array and then use it:

             D o = target.get(0);
    
             D oNew = (D)((BaseClass)o).clone();
             target.add(oNew);
    

    Polymorphism will take care of the rest 🙂

    The second one is not a real ‘solution’, but can be used if all you want is a new instance for an array of objects parameterized by type. Type Erasure only happens for parameterized types, but it does not happen for basic arrays (arrays are reified in JVM). So if we have the freedom to change the signature of the method and working with arrays is ok, then the following would work:

        public <D extends BaseClass> boolean doIt(D[] target) {
        try {
            D newD = (D) (target.getClass().getComponentType().getConstructor(int.class).newInstance(8));
            target[0] = newD;
    
            // The following is optional, if we want to work with Collections internally
            List<D> l = new ArrayList<D>(Arrays.asList(target));
            l.add(newD);  
    
    
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    

    Note: Super type tokens would not work for this problem if we cannot introduce new parameters. Please correct me if I’m wrong.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider the following code: @Entity @Table(name = a) public class A implements Serializable {
Consider the following code: public class MyClass { public static string MyStaticMethod() { //string
Consider the following code: #include <iostream> using namespace std; class Test { static int
Consider the following code :- public class UsingWait1{ public static void main(String... aaa){ CalculateSeries
Consider the following code in a DLL: public class ReceivingClass { private Assembly myAssembly;
Consider the following code: abstract class SomeClassX<T> { // blah } class SomeClassY: SomeClassX<int>
Consider the following code: public abstract class RepositoryBase<T> where T : class { #region
Consider following code public class City { public string Name { get { return
Consider the following code, public class StartUp { public StartUp(String[] test){} public static void
Consider the following code which does not rollback the transaction if an exception is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.