Java init ошибка

What does signify in a Java exception? For example: BlahBlahException... at java.io.FileInputStream.(FileInputStream.java:20)

What does <init> signify in a Java exception?

For example:

BlahBlahException...

at java.io.FileInputStream.<init>(FileInputStream.java:20)

Pops's user avatar

Pops

29.8k37 gold badges133 silver badges151 bronze badges

asked Aug 3, 2012 at 5:48

1

That the exception is thrown in the construction of the object, there are two options:

  • in the constructor
  • while initializing variables

Check out this demo I wrote: http://ideone.com/Mm5w5


class Main
{
        public static void main (String[] args) throws java.lang.Exception
        {
                try
                { new Test(); } catch (Exception e) { e.printStackTrace(); }

                try
                { new Test2(); } catch (Exception e) { e.printStackTrace(); }

                try
                { new Test3(); } catch (Exception e) { e.printStackTrace(); }


        }

        static class Test
        {
                Object obj = getObject();
                Object getObject()
                { throw new RuntimeException("getObject"); }
        }

        static class Test2
        {
                Test2()
                {
                        throw new RuntimeException("constructor");
                }
        }

        static class Test3
        {
                Object obj1 = null;
                String str = obj1.toString();
        }
}

Produces:

java.lang.RuntimeException: getObject
    at Main$Test.getObject(Main.java:24)
    at Main$Test.<init>(Main.java:22)
    at Main.main(Main.java:9)
java.lang.RuntimeException: constructor
    at Main$Test2.<init>(Main.java:31)
    at Main.main(Main.java:12)
java.lang.NullPointerException
    at Main$Test3.<init>(Main.java:38)
    at Main.main(Main.java:15)

answered Aug 3, 2012 at 5:50

Martijn Courteaux's user avatar

Martijn CourteauxMartijn Courteaux

66.8k46 gold badges194 silver badges285 bronze badges

<init>

is called

Instance Initialization method

which is created by your java compiler from the constructor you have defined. Though it is not valid method definition, your JVM expects this and anything that you put in the constructor will be executed in method. So when you an exception with from , you can be sure that it is from the constructor of the executed java class. Read more about this on Bill venner’s design technique articles on Object Initialization.

answered Aug 3, 2012 at 5:59

sakthisundar's user avatar

sakthisundarsakthisundar

3,2383 gold badges15 silver badges29 bronze badges

method init in class Preferences cannot be applied to given types;
required: String
found: no arguments
reason: actual and formal argument lists differ in length

and Preferences.init(); is marked red in NetBeans

I do not know what the problem is?

When running I get the following error:

    Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: processing.app.Preferences.init
    at arduinojava.ArduinoJava.main(ArduinoJava.java:34)
Java Result: 1

Here is the code:

/*
* This class will get the input from arduino board and output
* the data to the scanner
* Code adopted from Silveira Neto
*/

package arduinojava;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.InputStream;
import java.io.OutputStream;
import processing.app.Preferences;

/**
*
* @author kinley tshering
*/
public class ArduinoJava {

static InputStream input;
static OutputStream output;
static CommPortIdentifier portId;
static SerialPort port;

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
  //code application logic here

     Preferences.init();
     System.out.println("Using port: " + Preferences.get("serial.port"));
    try {
            portId = CommPortIdentifier.getPortIdentifier(
                   Preferences.get("serial.port"));

          //port = (SerialPort)portId.open("serial talk", 4000);
          port = (SerialPort)portId.open("", 4500);
          input = port.getInputStream();
          output = port.getOutputStream();
           port.setSerialPortParams(Preferences.getInteger("serial.debug_rate"),
                  SerialPort.DATABITS_8,
                  SerialPort.STOPBITS_1,
                  SerialPort.PARITY_NONE);

          while(true){
                      while(input.available() > 0) {
                                   System.out.print((char)(input.read()));
                       }
           }
  }
  catch(gnu.io.NoSuchPortException nsp)  {
       System.err.println("ERROR: " + nsp.getMessage());
   }
  catch(gnu.io.UnsupportedCommOperationException usp)  {
       System.err.println("ERROR: " + usp.getMessage());
   }
   catch(gnu.io.PortInUseException pie)  {
       System.err.println("ERROR: Port " + port + " is already in usenCLose the port and restart.");
   }
   catch(java.io.IOException ioe) {
       System.err.println("IO ERROR: " + ioe.getMessage() );
   }
   catch(Exception exe) {
       System.err.println("ERROR: Unexpected error occured n" + exe.getMessage() );
    }
}

}

asked Nov 29, 2012 at 22:32

MOTIVECODEX's user avatar

method init in class Preferences cannot be applied to given types;
required: String
found: no arguments

it seems you don’t have any method init() without parameters in Preferences class.

You need to call something like below:

Preferences.init("yourString");

NOTE: We don’t know what yourString should be exactly while invoking init() method.

answered Nov 29, 2012 at 22:34

kosa's user avatar

kosakosa

65.6k13 gold badges126 silver badges167 bronze badges

7

method init in class Preferences cannot be applied to given types;
required: String found: no arguments

The error says it all, your init() method is expecting a String argument and you are passing none.

This
Preferences.init();

should be

 Preferences.init("pass a string argument here");

answered Nov 29, 2012 at 22:34

PermGenError's user avatar

PermGenErrorPermGenError

45.7k8 gold badges86 silver badges106 bronze badges

method init in class Preferences cannot be applied to given types;
required: String
found: no arguments
reason: actual and formal argument lists differ in length

and Preferences.init(); is marked red in NetBeans

I do not know what the problem is?

When running I get the following error:

    Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: processing.app.Preferences.init
    at arduinojava.ArduinoJava.main(ArduinoJava.java:34)
Java Result: 1

Here is the code:

/*
* This class will get the input from arduino board and output
* the data to the scanner
* Code adopted from Silveira Neto
*/

package arduinojava;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.InputStream;
import java.io.OutputStream;
import processing.app.Preferences;

/**
*
* @author kinley tshering
*/
public class ArduinoJava {

static InputStream input;
static OutputStream output;
static CommPortIdentifier portId;
static SerialPort port;

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
  //code application logic here

     Preferences.init();
     System.out.println("Using port: " + Preferences.get("serial.port"));
    try {
            portId = CommPortIdentifier.getPortIdentifier(
                   Preferences.get("serial.port"));

          //port = (SerialPort)portId.open("serial talk", 4000);
          port = (SerialPort)portId.open("", 4500);
          input = port.getInputStream();
          output = port.getOutputStream();
           port.setSerialPortParams(Preferences.getInteger("serial.debug_rate"),
                  SerialPort.DATABITS_8,
                  SerialPort.STOPBITS_1,
                  SerialPort.PARITY_NONE);

          while(true){
                      while(input.available() > 0) {
                                   System.out.print((char)(input.read()));
                       }
           }
  }
  catch(gnu.io.NoSuchPortException nsp)  {
       System.err.println("ERROR: " + nsp.getMessage());
   }
  catch(gnu.io.UnsupportedCommOperationException usp)  {
       System.err.println("ERROR: " + usp.getMessage());
   }
   catch(gnu.io.PortInUseException pie)  {
       System.err.println("ERROR: Port " + port + " is already in usenCLose the port and restart.");
   }
   catch(java.io.IOException ioe) {
       System.err.println("IO ERROR: " + ioe.getMessage() );
   }
   catch(Exception exe) {
       System.err.println("ERROR: Unexpected error occured n" + exe.getMessage() );
    }
}

}

asked Nov 29, 2012 at 22:32

MOTIVECODEX's user avatar

method init in class Preferences cannot be applied to given types;
required: String
found: no arguments

it seems you don’t have any method init() without parameters in Preferences class.

You need to call something like below:

Preferences.init("yourString");

NOTE: We don’t know what yourString should be exactly while invoking init() method.

answered Nov 29, 2012 at 22:34

kosa's user avatar

kosakosa

65.6k13 gold badges126 silver badges167 bronze badges

7

method init in class Preferences cannot be applied to given types;
required: String found: no arguments

The error says it all, your init() method is expecting a String argument and you are passing none.

This
Preferences.init();

should be

 Preferences.init("pass a string argument here");

answered Nov 29, 2012 at 22:34

PermGenError's user avatar

PermGenErrorPermGenError

45.7k8 gold badges86 silver badges106 bronze badges

A java.lang.InstantiationException is thrown when JVM cannot instantiate a type at runtime.

To make this definition more elaborate. A java.lang.InstantiationException can be thrown when you try to create an instance of a non-instantiable type or a legit concrete class without having nullary constructor, dynamically during runtime using Class.newInstance() method.

To be more specific, you get java.lang.InstantiationException under below circumstances.

  • Passing the fully qualified name of abstract class name or interface to Class.forName as a String while creating instance of Class
  • Creating Class instance using abstract class or interface or array or primitive type by using their “.class” attribute
  • Passing the name of Interface to Class.forName

In Java, you can create an instance of a class at runtime using Class type, provided that the given class is a concrete class.

Creating an instance using Class.newInstance of a known class

Class<Animal> c = String.class;
String str = c.newInstance();

Creating an instance using Class.newInstance of an unknown class loaded with Class.forName

Class c = Class.forName("java.lang.String");
String str = (String) c.newInstance();

These are the two ways of instantiating and we generally use either of one. But we may get java.lang.InstantiationException when we are instantiating in this way. Java enforce you to declare or handle java.lang.InstantiationException when you are using Class.newInstance() method to create instances. So, let’s discuss why do we get java.lang.InstantiationException with this style of coding.

When the Type is Non-instantiable

There are few types which we cannot instantiate. We cannot instantiate an abstract class, an interface, an Array or any Java primitive type using new keyword. Java compiler will throw error immediately if we are attempting that. However, we can also write code to create an instance of type using Class.newInstance. While loading the class we provide the class name withing double quotes to Class.forName() method or use the “.class” attribute the type which returns a Class object as shown above.

In this approach, there is a possibility that you can provide a class name which can’t be instantiated, and Java Compiler ignores them during compilation time. However, at runtime when JVM tries create an instance of that type, it realizes that it can’t be instantiated and throws java.lang.InstantiationException.

So, you need to go back and check if you are creating in this style, you are making sure that you are using concrete Java class only.

Below are few examples, in which java.lang.InstantiationException is thrown.

When you attempt to instantiate abstract class

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

abstract class Alpha {

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Class.forName("com.techstackjournal.Alpha");

 // Can also be written as, Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();
	}

}
Exception in thread "main" java.lang.InstantiationException
	at java.base/jdk.internal.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
	at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
	at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:350)
	at java.base/java.lang.Class.newInstance(Class.java:645)
	at com.techstackjournal.InitializationExceptionDemo.main(InitializationExceptionDemo.java:15)

When you attempt to instantiate interface type

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

interface Alpha {

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Class.forName("com.techstackjournal.Alpha");

 // Can also be written as, Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();
	}

}
Exception in thread "main" java.lang.InstantiationException: com.techstackjournal.Alpha
	at java.base/java.lang.Class.newInstance(Class.java:639)
	at com.techstackjournal.InitializationExceptionDemo.main(InitializationExceptionDemo.java:16)
Caused by: java.lang.NoSuchMethodException: com.techstackjournal.Alpha.<init>()
	at java.base/java.lang.Class.getConstructor0(Class.java:3508)
	at java.base/java.lang.Class.newInstance(Class.java:626)
	... 1 more

When the Type doesn’t have a Nullary Constructor

If the class that you are instantiating doesn’t contain a nullary constructor and you are attempting to create an instance of that class using Class.forName method, java.lang.InstantiationException will be thrown.

A nullary constructor is a constructor without any arguments.

So, when we try to instantiate a class using Class.newInstance() as below, it tries to create an instance using empty constructor (or nullary constructor). Since our code doesn’t have a nullary constructor JVM throws java.lang.InstantiationException. Look below to this code snippet on how we can resolve this kind of issues.

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

class Alpha {

	public Alpha(String arg1) {

	}

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Class.forName("com.techstackjournal.Alpha");

 // Can also be written as, Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();

	}

}
Exception in thread "main" java.lang.InstantiationException: com.techstackjournal.Alpha
	at java.base/java.lang.Class.newInstance(Class.java:639)
	at com.techstackjournal.InitializationExceptionDemo.main(InitializationExceptionDemo.java:20)
Caused by: java.lang.NoSuchMethodException: com.techstackjournal.Alpha.<init>()
	at java.base/java.lang.Class.getConstructor0(Class.java:3508)
	at java.base/java.lang.Class.newInstance(Class.java:626)
	... 1 more

How to fix java.lang.InstantiationException caused by nullary constructor

There are 2 solutions to fix this issue.

  1. First obvious solution is to add a constructor to the class without arguments. But sometimes it is possible that the class being used is within a jar file is not accessible to make changes to it, where our 2nd solution comes into the picture.
  2. If the above solution is not possible, may be due to the fact that the class is within a jar file, you can use the existing constructor explicitly while creating the instance using Class.getDeclaredConstructor(Class).newInstance(arguments)

Fixing java.lang.InstantiationException by Adding Nullary Constructor

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

class Alpha {

	public Alpha(String arg1) {
		// do something
	}

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();

	}

}

You may have the code as given in the above code snippet which is causing java.lang.InstantiationException. I can fix that issue just by adding a nullary method or no-argument constructor as below.

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

class Alpha {
	
	public Alpha() {
		System.out.println("Success");
	}

	public Alpha(String arg1) {
		// do something
	}

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();

	}

}

Fixing java.lang.InstantiationException by Calling Specific Constructor

As mentioned above, we can call a specific constructor while creating instance using newInstance method with the help of Class.getDeclaredConstructor method. The Class.getDeclaredConstructor method takes one or more arguments of type Class, which tells the JVM to look for constructors with that signature. For example, if I pass List.class and String.class as arguments, we are telling the JVM to look for a constructor that has its first argument as List and second argument as String. Then JVM will make use of that specific constructor to create the instance instead of searching for the default nullary constructor.

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

class Alpha {

	public Alpha(String arg1) {
		System.out.println(arg1);
	}

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Alpha.class;
		Alpha a = (Alpha) c.getDeclaredConstructor(String.class).newInstance("test");

	}

}

Best Java code snippets using java.lang.NoSuchMethodError.<init> (Showing top 20 results out of 1,782)

  private static Method init() {
    try {
      Method m = ClassLoader.class.getDeclaredMethod("findResource", String.class);
      m.setAccessible(true);
      return m;
    } catch (NoSuchMethodException e) {
      throw (Error)new NoSuchMethodError().initCause(e);
    }
  }
}
public Constructor<T> run() {
  try {
    return clazz.getDeclaredConstructor(paramTypes);
  } catch (NoSuchMethodException e) {
    throw new NoSuchMethodError(e.getMessage());
  }
}




private static Class<?> getArgumentType(ArgumentMatcher<?> argumentMatcher) {
  Method[] methods = argumentMatcher.getClass().getMethods();
  for (Method method : methods) {
    if (isMatchesMethod(method)) {
      return method.getParameterTypes()[0];
    }
  }
  throw new NoSuchMethodError("Method 'matches(T)' not found in ArgumentMatcher: " + argumentMatcher + " !rn Please file a bug with this stack trace at: https://github.com/mockito/mockito/issues/new ");
}
  public Constructor<OptionalDataException> run() {
    try {
      final Constructor<OptionalDataException> constructor = OptionalDataException.class.getDeclaredConstructor(boolean.class);
      constructor.setAccessible(true);
      return constructor;
    } catch (NoSuchMethodException e) {
      throw new NoSuchMethodError(e.getMessage());
    }
  }
});
private static Method findCallback(Class<?> cls, String methodName) {
  for (Method m : cls.getDeclaredMethods()) {
    if (m.getName().equals(methodName)) {
      return m;
    }
  }
  throw new NoSuchMethodError(methodName);
}

public FastMethod getMethod(String name, Class[] parameterTypes) {
  try {
    return getMethod(type.getMethod(name, parameterTypes));
  } catch (NoSuchMethodException e) {
    throw new NoSuchMethodError(e.getMessage());
  }
}
public FastConstructor getConstructor(Class[] parameterTypes) {
  try {
    return getConstructor(type.getConstructor(parameterTypes));
  } catch (NoSuchMethodException e) {
    throw new NoSuchMethodError(e.getMessage());
  }
}
  private static NoSuchMethodError newNoSuchConstructorInternalError(Class declaringType, Class[] argumentTypes) {
    Stream<String> stringStream = Arrays.stream(argumentTypes).map(Class::getSimpleName);
    String argsAsText = stringStream.collect(Collectors.joining(","));

    return new NoSuchMethodError("Micronaut constructor " + declaringType.getName() + "(" + argsAsText + ") not found. Most likely reason for this issue is that you are running a newer version of Micronaut with code compiled against an older version. Please recompile the offending classes");
  }
}






public static NoSuchMethodError newNoSuchMethodError(Class declaringType, String name, Class[] argumentTypes) {
  Stream<String> stringStream = Arrays.stream(argumentTypes).map(Class::getSimpleName);
  String argsAsText = stringStream.collect(Collectors.joining(","));
  return new NoSuchMethodError("Required method " + name + "(" + argsAsText + ") not found for class: " + declaringType.getName() + ". Most likely cause of this error is that an unsupported or older version of a dependency is present on the classpath. Check your classpath, and ensure the incompatible classes are not present and/or recompile classes as necessary.");
}
private static NoSuchMethodError newNoSuchMethodInternalError(Class declaringType, String name, Class[] argumentTypes) {
  Stream<String> stringStream = Arrays.stream(argumentTypes).map(Class::getSimpleName);
  String argsAsText = stringStream.collect(Collectors.joining(","));
  return new NoSuchMethodError("Micronaut method " + declaringType.getName() + "." + name + "(" + argsAsText + ") not found. Most likely reason for this issue is that you are running a newer version of Micronaut with code compiled against an older version. Please recompile the offending classes");
}
public FastMethod getMethod(String name, Class[] parameterTypes) {
  try {
    return getMethod(type.getMethod(name, parameterTypes));
  } catch (NoSuchMethodException e) {
    throw new NoSuchMethodError(e.getMessage());
  }
}
public FastConstructor getConstructor(Class[] parameterTypes) {
  try {
    return getConstructor(type.getConstructor(parameterTypes));
  } catch (NoSuchMethodException e) {
    throw new NoSuchMethodError(e.getMessage());
  }
}
public FastMethod getMethod(String name, Class[] parameterTypes) {
  try {
    return getMethod(type.getMethod(name, parameterTypes));
  } catch (NoSuchMethodException e) {
    throw new NoSuchMethodError(e.getMessage());
  }
}
public FastConstructor getConstructor(Class[] parameterTypes) {
  try {
    return getConstructor(type.getConstructor(parameterTypes));
  } catch (NoSuchMethodException e) {
    throw new NoSuchMethodError(e.getMessage());
  }
}





public static @Nonnull SubTask getParentOf(@Nonnull Executable e) 
    throws Error, RuntimeException {
  try {
    return e.getParent();
  } catch (AbstractMethodError ignored) { 
    try {
      Method m = e.getClass().getMethod("getParent");
      m.setAccessible(true);
      return (SubTask) m.invoke(e);
    } catch (IllegalAccessException x) {
      throw (Error)new IllegalAccessError().initCause(x);
    } catch (NoSuchMethodException x) {
      throw (Error)new NoSuchMethodError().initCause(x);
    } catch (InvocationTargetException x) {
      Throwable y = x.getTargetException();
      if (y instanceof Error)     throw (Error)y;
      if (y instanceof RuntimeException)     throw (RuntimeException)y;
      throw new Error(x);
    }
  }
}
private Method getMethod(String methodName, Object... arguments) throws Exception {
 METHODS:
 for (Method method : lockLikeObject.getClass().getMethods()) {
  Class<?>[] parameterTypes = method.getParameterTypes();
  if (method.getName().equals(methodName) && (parameterTypes.length == arguments.length)) {
   for (int i = 0; i < arguments.length; i++) {
    if (!parameterTypes[i].isAssignableFrom(arguments[i].getClass())) {
     continue METHODS;
    }
   }
   return method;
  }
 }
 throw new NoSuchMethodError(methodName);
}
@Test
public void stopCannotResume() {
  OnNextFailureStrategy strategy = OnNextFailureStrategy.stop();
  assertThat(strategy.test(new IllegalStateException(), null))
      .isFalse();
  assertThat(strategy.test(new NoSuchMethodError(), null))
      .isFalse();
}
@SuppressWarnings("deprecation")
@Test
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public void testDoesNotThrowIfAskedToGetManagerForFragmentPreJellyBeanMr1() {
 Util.setSdkVersionInt(Build.VERSION_CODES.JELLY_BEAN);
 Activity activity = Robolectric.buildActivity(Activity.class).create().start().resume().get();
 android.app.Fragment fragment = new android.app.Fragment();
 activity.getFragmentManager().beginTransaction().add(fragment, "test").commit();
 android.app.Fragment spyFragment = Mockito.spy(fragment);
 when(spyFragment.getChildFragmentManager()).thenThrow(new NoSuchMethodError());
 assertNotNull(retriever.get(spyFragment));
}
@Test
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public void testDoesNotThrowIfAskedToGetManagerForActivityPreJellYBeanMr1() {
 Util.setSdkVersionInt(Build.VERSION_CODES.JELLY_BEAN);
 Activity activity = Robolectric.buildActivity(Activity.class).create().start().resume().get();
 Activity spyActivity = Mockito.spy(activity);
 when(spyActivity.isDestroyed()).thenThrow(new NoSuchMethodError());
 assertNotNull(retriever.get(spyActivity));
}
@Test
public void stopProcessWithFatal() {
  OnNextFailureStrategy strategy = OnNextFailureStrategy.stop();
  Throwable exception = new NoSuchMethodError("foo");
  assertThatExceptionOfType(NoSuchMethodError.class)
      .isThrownBy(() -> strategy.process(exception, null, Context.empty()))
      .satisfies(e -> assertThat(e)
          .hasMessage("foo")
          .hasNoSuppressedExceptions());
}

Когда я запускаю свой код, в консоли появляется ошибка.

"at com.tutorial.main.Game.<init>(Game.java:12)
    at com.tutorial.main.Window.<init>(Window.java:21)"

Код:

package com.tutorial.main;

import java.awt.Canvas;

public class Game extends Canvas implements Runnable {

  private static final long serialVersionUID = 7580815534084638412L;

  public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;

  public Game() {
    new Window(WIDTH, HEIGHT, "Lets Build a Game!");
  }

  public synchronized void start() {

  }
  public void run() {

  }
  public static void main(String args[]) {
    new Game();
  }
}

Это второй файл видимо они оба как-то битые?

package com.tutorial.main;

import java.awt.Canvas;
import javax.swing.*;
import java.awt.Dimension;

public class Window extends Canvas {

  private static final long serialVersionUID = -240840600533728354L;

  public Window(int width, int height, String title) {
    JFrame frame = new JFrame(title);

    frame.setPreferredSize(new Dimension(width, height));
    frame.setMinimumSize(new Dimension(width, height));
    frame.setMaximumSize(new Dimension(width, height));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    Game game = new Game();
    frame.add(game);
    frame.setVisible(true);
    game.start();

  }

}

Кто-нибудь знает, как это исправить.

3 ответа

Лучший ответ

Удалить new window() из конструктора игрового класса.

Удалить new game(); из основного метода.

Добавить new Window(WIDTH, HEIGHT, "Lets Build a Game!"); в основной метод

import java.awt.Canvas;

public class Game extends Canvas implements Runnable {

    private static final long serialVersionUID = 7580815534084638412L;

    public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;

    public Game() {
       // removed line new window()
    }

    public synchronized void start() {

    }

    public void run() {

    }

    public static void main(String args[]) {
       // removed line new game()
       new Window(WIDTH, HEIGHT, "Lets Build a Game!"); // added this line here
    }
}

Нота

Не расширяйте класс Window с помощью холста. это не нужно.


0

Madhawa Priyashantha
1 Авг 2015 в 06:26

Использовать

 Window(int width, int height, String title, Game game)

Вместо того

 Window(int width, int height, String title)

Использовать

 new Window(WIDTH, HEIGHT, "Lets Build a Game!",this);

Передача текущего объекта класса (this). Так что нет необходимости снова создавать объект класса Game

Вместо того

new Window(WIDTH, HEIGHT, "Lets Build a Game!");

И еще один, вы снова создаете объект класса Game в классе Window, который ему нужен.

  Game game = new Game();

Window.java

import java.awt.Canvas;
import javax.swing.*;
import java.awt.Dimension;

public class Window extends Canvas {

  private static final long serialVersionUID = -240840600533728354L;

  public Window(int width, int height, String title, Game game) {
    JFrame frame = new JFrame(title);

    frame.setPreferredSize(new Dimension(width, height));
    frame.setMinimumSize(new Dimension(width, height));
    frame.setMaximumSize(new Dimension(width, height));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    //Game game = new Game();//you are again creating Game class object here it gives you an error.
    frame.add(game);
    frame.setVisible(true);
    game.start();

  }

}

Game.java

import java.awt.Canvas;

public class Game extends Canvas implements Runnable {

  private static final long serialVersionUID = 7580815534084638412L;

  public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;

  public Game() {
    new Window(WIDTH, HEIGHT, "Lets Build a Game!",this);//passing current class object 
  }

  public synchronized void start() {

  }
  public void run() {

  }
  public static void main(String args[]) {
    new Game();
  }
}


0

SatyaTNV
1 Авг 2015 в 06:24

New Game() вызывает new Window(), который вызывает новый Game(), который вызывает новый Window() и т. д. и т. д. — это код, который никогда не останавливается.

В первой строке ошибки, вероятно, должно быть указано, что это «переполнение стека».


1

Florian Schaetz
1 Авг 2015 в 05:59

Понравилась статья? Поделить с друзьями:
  • Java heap space ошибка как исправить minecraft
  • Java heap space ошибка как исправить edeclaration
  • Java heap space ошибка как исправить dbeaver
  • Java fatal error unable to find package java lang in classpath or bootclasspath
  • Java executable not found error