Class newinstance java lang instantiationexception

How to resolve a «java.lang.InstantiationException»?

I debugged this by the reason for the exception, ‘Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.’ I’m parsing in an XML file using SAX but when I call the class loader on the class, a is thrown.

How to resolve a «java.lang.InstantiationException»?

I’m parsing in an XML file using SAX but when I call the class loader on the class, a java.lang.InstantiationException is thrown.

I debugged this by the reason for the exception, ‘Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.’

But the location class isn’t an interface or abstract class. I’ve also checked that the class is in the correct package and it is.

Does anyone have any idea why the exception is being thrown in this case?

The exception is being thrown just after the first println in the startElement of the Parser class:

public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException < if (qName.equals("location"))< location = true; System.out.println("Found a location. "); //exception thrown after this statement as shown //in the error output below try < //Read in the values for the attributes of the element int locationID = Integer.parseInt(atts.getValue("id")); String locationName = atts.getValue("name"); //Generate a new instance of Location on-the-fly using reflection. The statement Class.forName("gmit.Location").newInstance(); invokes the //Java Class Loader and the calls the null (default) constructor of Location. Location loc = (Location) Class.forName("gmit.Location").newInstance(); loc.setId(locationID); //Now configure the Location object with an ID, Name, Description etc. loc.setName(locationName); > catch (Exception e) < e.printStackTrace(); >>else if (qName.equals("description"))< description = true; System.out.println("Found a description. You should tie this to the last location you encountered. "); >else if (qName.equals("exits"))< exits = true; System.out.println("Found an exit. You should tie this to the last location you encountered. "); >else if (qName.equals("item"))< item = true; System.out.println("Found an item. You should tie this to the last game-character you encountered if the boolean gameCharacter flag is true. "); >else if (qName.equals("game-character"))< gameCharacter = true; System.out.println("Found a game character. "); >else if (qName.equals("search-algorithm")) < searchAlgorithm = true; System.out.println("Found a search algo. You should tie this to the last game-character you encountered if the boolean gameCharacter flag is true. "); >> 

My complete location class:

Читайте также:  Connect to mysql with java jdbc

The errors being thrown during run time:

Your Location class does not have a no-args constructor. (It has two constructors with declared arguments . so there is no default no-args constructor.)

  • Add a no-args constructor.
  • Reflectively lookup one of the Constructor objects on the Location Class object and invoke it using Constructor.newInstance(. ) with arguments that give the actual constructor argument values.

It looks like the first option is the better one in this context . ‘cos it looks like you don’t have the required argument values at that point in the code.

Java.lang.InstantiationException: java.lang.Class cannot, java.lang.InstantiationException: java.lang.Class cannot be instantiated at java.lang.Class.newInstance(Native Method) android. Share. …

Java InstantiationException

I made a class to implement an interface and was testing it using another class.

This is the class that I created.

public class MyWeaponI implements WeaponI < Random RAND = new Random(); private int maxDamage; private String name; public MyWeaponI(String name1)< maxDamage = 10; name = name1; >@Override public int getDamage() < return RAND.nextInt(maxDamage)+1; >@Override public int getMaxDamage() < return maxDamage; >@Override public String toString() < return String.format("Weapon %s, damage=%d", name, maxDamage); >@Override public void initFromString(String input) < Scanner s = new Scanner(input); s.useDelimiter("$n"); String pattern = "(\\w+)\\s*,\\s*(\\d)\\s*"; if(s.hasNext(pattern))< MatchResult m = s.match(); maxDamage = Integer.parseInt(m.group(2)); name = m.group(1); System.out.println(String.format("Weapon %s, damage=%d", m.group(1), Integer.parseInt(m.group(2)))); >> @Override public String getName() < return name; >> 

This is the part of the tester that I get the error in. I just took out part of the tester to reduce the amount of code that I was posting. If you need the full tester I can change it.

Class warriorClass = null, weaponClass = null, diskClass = null; for(int i=0;i assert weaponClass != null : "You need to supply a weapon class"; WeaponI weapon = (WeaponI)weaponClass.newInstance(); testWeapon(weapon); 

When I run the code, I get an InstatiationException on the line of the tester that starts with «WeaponI weapon» near the bottom. There are two other classes that that also need to be passed to the tester and I’m assuming that both of them will also have to same problem. I honestly have no idea how to fix the problem, so any help would be much appreciated.

Exception in thread "main" java.lang.InstantiationException: warriorsandweapons.MyWeaponI at java.lang.Class.newInstance(Class.java:368) at warriorsandweapons.Arena.main(Arena.java:308) Java Result: 1 

For Class.newInstance to work it needs a default constructor. You can add a default constructor to MyWeapon class and try.

Quoting from javadoc for Class

InstantiationException — if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.

You’re doing the following:

WeaponI weapon = (WeaponI)weaponClass.newInstance(); 

On class warriorsandweapons.MyWeaponI . This class has only one constructor, and it’s a constructor that takes a single argument.

If you look at the Javadoc for Class.newInstance() you see the following note:

The class is instantiated as if by a new expression with an empty argument list.

So you can only use newInstance if there is a constructor that doesn’t take arguments. There is no such constructor on MyWeaponI , that’s why you get this exception.

Instead, you can use java.lang.reflect.Constructor to create the instance and pass arguments:

Class weaponClass; // . Constructor constructor = weaponClass.getConstructor(String.class); WeaponI instance = constructor.newInstance(nameArgument); 

Android, java.lang.InstantiationException. I am making an app to send X amount of texts to people and after re-writing my code to include threads, it …

How to fix java.lang.InstantiationException?

I’m trying to export my database using FAB. This is the error

Everything was working until I inserted this codes:

FloatingActionButton fab1 = (FloatingActionButton) findViewById(R.id.fab1); fab1.setOnClickListener(new View.OnClickListener() < Intent sIntent = getIntent(); ExampleClass sClass = sIntent.getParcelableExtra("selected"); String selCode = sClass.getqCode(); @Override public void onClick(View v) < exportDataBaseIntoCSV(); >>); > public void exportDataBaseIntoCSV() < Intent sIntent = getIntent(); ExampleClass sClass = sIntent.getParcelableExtra("selected"); String selCode = sClass.getqCode(); ClassDB db = new ClassDB(context);//here CredentialDb is my database. you can create your db object. File exportDir = new File(Environment.getExternalStorageDirectory(), ""); if (!exportDir.exists()) < exportDir.mkdirs(); >File file = new File(exportDir, selCode +".csv"); try < file.createNewFile(); CSVWriter csvWrite = new CSVWriter(new FileWriter(file)); SQLiteDatabase sql_db = db.getReadableDatabase();//here create a method ,and return SQLiteDatabaseObject.getReadableDatabase(); Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+selCode,null); csvWrite.writeNext(curCSV.getColumnNames()); while(curCSV.moveToNext()) < //Which column you want to export you can add over here. String arrStr[] =; csvWrite.writeNext(arrStr); > csvWrite.close(); curCSV.close(); > catch(Exception sqlEx) < Log.e("Error:", sqlEx.getMessage(), sqlEx); >> 

This is the first time that I see this error so I don’t have any idea how can I fix this.

It seems like the object cant get instantiated.Try adding a parameterized constructor in the class.

I think you should not write this code:

Intent sIntent = getIntent(); ExampleClass sClass = sIntent.getParcelableExtra("selected"); String selCode = sClass.getqCode(); 

Inside your new View.OnClickListener() anonymous class. It is not in any method, and is already written inside exportDataBaseIntoCSV() method.

Java.lang.InstantiationException android, 1. Remove this line, it’s useless and the cause of your problem. You can’t manually instantiate Services/Activities in Android, it forbids it and hence …

Источник

How to Resolve the Instantiation Exception in Java

How to Resolve the Instantiation Exception in Java

The InstantiationException is a runtime exception in Java that occurs when an application attempts to create an instance of a class using the Class.newInstance() method, but the specified class object cannot be instantiated.

Since the InstantiationException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.

What Causes InstantiationException

The InstantiationException is thrown when the JVM cannot instantiate a type at runtime. This can happen for a variety of reasons, including the following:

  • The class object represents an abstract class, interface, array class, primitive or void .
  • The class has no nullary constructor. Such a constructor is required when a parameterized constructor is defined for the class.

InstantiationException Example

Here is an example of an InstantiationException thrown when the Class.newInstance() method is used to create an instance of a boolean :

public class InstantiationExceptionExample < public static void main(String[] args) < try < Classclazz = boolean.class; clazz.newInstance(); > catch (InstantiationException ie) < ie.printStackTrace(); >catch (IllegalAccessException iae) < iae.printStackTrace(); >> >

Since boolean is a primitive data type, a new instance of it cannot be created using the Class.newInstance() method, which can only construct objects for concrete classes. Running the above code throws the following exception:

java.lang.InstantiationException: boolean at java.base/java.lang.Class.newInstance(Class.java:598) at InstantiationExceptionExample.main(InstantiationExceptionExample.java:5) Caused by: java.lang.NoSuchMethodException: boolean.() at java.base/java.lang.Class.getConstructor0(Class.java:3427) at java.base/java.lang.Class.newInstance(Class.java:585) . 1 more

How to Resolve InstantiationException

To avoid the InstantiationException , it should be ensured that the instance of the class that is attempted to be created at runtime using Class.newInstance() is a concrete class and not an abstract class, interface, array class, primitive or void.

If it is a concrete class, it should be ensured that the class has a nullary constructor (in case it contains a parameterized constructor). If this is not possible, the Constructor objects can be reflectively looked up and used to construct a new instance of the class using Constructor.newInstance(args) with arguments that pass the actual constructor argument values.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever.

Источник

Оцените статью