Java method argument type mismatch

Размышления IllegalArgumentException причины

ОБНОВЛЕНИЕ. Чтобы сделать вопрос более ясным. Какова возможная причина получения ClassCastException при вызове метода с помощью отражений? Я получил следующую стекю в качестве части моего приложения, пытаясь вызвать метод с помощью отражений.

java.lang.IllegalArgumentException: [email protected] at sun.reflect.GeneratedMethodAccessor332.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com. (remaining is my method stack trace) 

Я попробовал примерный класс и передал ему различные аргументы разных типов, но я всегда получаю это исключение.

java.lang.IllegalArgumentException: argument type mismatch at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) 

ОБНОВЛЕНИЕ — Вот пример кода, который я написал, чтобы попытаться воссоздать исключение Интерфейс для создания класса прокси

package my.tests; public interface ReflectionsInterface
package my.tests; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Reflections implements ReflectionsInterface < public static void main(String[] args) < Reflections reflections = new Reflections(); ReflectionsInterface reflectionsProxy = reflections.createProxy(ReflectionsInterface.class); invokeMethod(reflectionsProxy, "doSomething", null); >public T createProxy(Class entityInterface) < EntityInvocationHandler eih = new EntityInvocationHandler(this); T cast = entityInterface.cast(Proxy.newProxyInstance( entityInterface.getClassLoader(), new Class[], eih)); return cast; > public static void invokeMethod(Object obj, String methodName, Object. args) < Method[] methods = obj.getClass().getMethods(); try < for (Method method : methods) < if (method.getName().equals(methodName)) < method.invoke(obj, args); break; >> > catch (Exception e) < e.printStackTrace(); >> public void doSomething() < System.out.println("woo"); >private final static class EntityInvocationHandler implements InvocationHandler, ReflectionsInterface < private Reflections reflectionObj; public EntityInvocationHandler(Reflections reflectionObj) < super(); this.reflectionObj = reflectionObj; >@Override public void doSomething() < reflectionObj.doSomething(); >@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable < Object invoke = method.invoke(this, args); return invoke; >> > 

Я не могу понять, когда я получу несоответствие типа аргумента, и будет вызвано ClassCastException. Я не могу воссоздать исключение и хотел бы знать, почему это происходит. Любой рабочий код, который его воссоздал, или ссылка на исходный код, выбрасывающая это исключение в этом случае, будут хорошими Я прошел через javaadocs и исходный код Method.class, я не могу понять, почему эта ошибка возникает.

Читайте также:  Simple Animated GIF web page

Недавние изменения, внесенные в код, исключили возникшее исключение. Вы говорите, что все еще получаете ошибки даже с этим новым SSCCE? Если нет, вернитесь к предыдущему коду, который на самом деле иллюстрирует возникшую проблему.

Ошибка исходит из кода моего приложения, который очень сложен, и я не могу опубликовать здесь. Это моя (неудачная) попытка заново создать ошибку или понять, почему она возникает ..

Источник

Java method argument type mismatch

The emergence of this anomaly

Severe: Servlet.service () for servlet action threw exception java.lang.IllegalArgumentException:argument type mismatch 

This exception, I looked at the code and found that it was not wrong, but why this error will burst it? Originally should be the parameter type mismatch error two appear, so long as the correct parameter type on the line, the emergence of this anomaly because: Struts framework ActionForm, has three main functions: assigns them automatically transformation and validation data . Wherein, in the automatic conversion of data types simplifies the programmer’s code amount, however, to Struts 1.2 Example: ActionForm java.util.Date data type (but by default has a java.sql.Date) Transition not provided.

When I said the following in the event of such an abnormality several commonly used several solutions:

Method a: Date Type Form uses the String type, in the Action own type conversion processing (i.e., for Form-> POJO conversion when manual handling in the Action).

Method two: Form use java.util.Date type, a custom class DateConverter date conversion (need to implement the interface Converter), and then registered in DateConverter Action ActionServlet or in a custom base class: ConvertUtils.register (newDateConverter (), Date .class).

Method Two specific approaches: 1. converting a first state class

package com.landray.kmss.tonly.dormitory.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.beanutils.Converter; public class UtilDateConverter implements Converter < @Override public Object convert(Class type, Object value) < System.out.println("UtilDateConverter.value=" + value); if (value == null) < return value; >if (value instanceof Date) < return value; >Date d = null; if (value instanceof String) < SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try < d = sdf.parse((String) value); >catch (ParseException e) < e.printStackTrace(); >> return d; > > 

2. And then the server starts Sheshi go to class registration
Method 1. Register servlet

package com.landray.kmss.tonly.dormitory.util; import java.util.Date; import javax.servlet.ServletException; import org.apache.commons.beanutils.ConvertUtils; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; public class UtilDateConverterInitWithPlugin implements PlugIn < public void init(ActionServlet servlet,ModuleConfig config)throws ServletException < System.out.println("UtilDateConverterInitWithPlugin.init()"); ConvertUtils.register(new UtilDateConverter(), Date.class); >@Override public void destroy() < >> 

Where the web.xml file with

 UtilDateConverterInitWithServlet com.bjsxt.struts.UtilDateConverterInitWithServlet 3  

Method 2. Use the struts of plug-in to register

package yg.util; import java.util.Date; import javax.servlet.ServletException; importorg.apache.commons.beanutils.ConvertUtils; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; public classUtilDateConverterInitWithPlugin implements PlugIn < public void destroy() < >public void init(ActionServlet servlet,ModuleConfig config) throws ServletException < System.out.println("UtilDateConverterInitWithPlugin.init()"); ConvertUtils.register(new UtilDateConverter(), Date.class); >> 

In which the struts-config.xml file plus

Источник

How to Fix Method/Constructor X in Class Y Cannot be Applied to Given Types in Java

How to Fix Method/Constructor X in Class Y Cannot be Applied to Given Types in Java

In computer programming, a function is a set of instructions that can be invoked to perform a particular task. In object-oriented programming (OOP), a method is a function that is typically associated with an object and models its behavior [1]. In Java, methods can also be static, in which case they are part of a class definition and do not require an object to be created before they are invoked.

Method Signature in Java

Every method has a unique method signature, which consists of the method name and its input parameters, which can be zero or more. Java methods also have return types, but these are not considered a part of the method signature, as it would be impossible for a compiler to distinguish between overloaded methods in certain contexts [2]. Below is an example of a method declaration with a method signature consisting of the method name “doSomething” and two method parameters; the 1st one of type String and name “param1,” and the 2nd one of type int with the name “param2.” It is important to note that method parameters always have a type and a name, and the order in which they appear in the method declaration matters.

Constructor signature in Java

Constructors are a special type of method invoked to create objects from a class. Constructors have no return type and always use the name of the class in which they are declared [3]. Similarly to method signatures, a constructor signature is made up of the constructor name and a comma-delimited list of input parameters enclosed in parentheses.

Method X in Class Y Cannot be Applied to Given Types & Constructor X in Class Y Cannot be Applied to Given Types

When performing semantic analysis, the Java compiler checks all method invocations for correctness. Whenever a method invocation doesn’t match the corresponding method signature, the method X in class Y cannot be applied to given types error is raised. This error is triggered by a method call attempted with the wrong number, type, and/or order of arguments.

Arguments are the actual data values passed to the method’s parameters during invocation. These have to match (or be safely convertible to) the parameters in the method signature, otherwise the aforementioned error will be raised.

Similarly, the constructor X in class Y cannot be applied to given types error is triggered whenever a constructor invocation doesn’t match the corresponding constructor signature, and the arguments passed on to the constructor don’t match the predefined parameters.

The messages produced upon compilation for these errors provide helpful information by specifying the following fields:

  1. “required”—the formal parameters expected by the method;
  2. “found”—the actual parameters (arguments) used to call the method; and
  3. “reason”—the specific cause for compilation failure.

Examples

Method X in Class Y Cannot be Applied to Given Types

The signature of the method on line 9 in Fig. 1 denotes a single String parameter, which means a single argument of type String is expected. If this method is invoked without an argument, the method X in class Y cannot be applied to given types error is raised, with an appropriate message that reads “actual and formal argument lists differ in length (Fig. 1(a)).” Likewise, if the greetPerson method is invoked with more than one argument, the same error will be raised (Fig. 2(b)). And if an argument of a different type is used instead, the same type of error is raised and the reason states an “argument mismatch” between the expected (required) and actual (found) argument, as shown in Fig. 1(c). Intuitively, calling the method with the appropriate number and type of arguments—a single String value in this particular case—rectifies the issue (Fig. 1(d)).

package rollbar; public class MismatchedMethodSig < public static void main(String. args) < greetPerson(); >static void greetPerson(String name) < System.out.println("Hello " + name); >>
MismatchedMethodSig.java:6: error: method greetPerson in class MismatchedMethodSig cannot be applied to given types; greetPerson(); ^ required: String found: no arguments reason: actual and formal argument lists differ in length
public class MismatchedMethodSig < public static void main(String. args) < greetPerson("John", 123); >static void greetPerson(String name) < System.out.println("Hello " + name); >>
MismatchedMethodSig.java:6: error: method greetPerson in class MismatchedMethodSig cannot be applied to given types; greetPerson("John", 123); ^ required: String found: String,int reason: actual and formal argument lists differ in length
1 2 3 4 5 6 7 8 9 10 11 12
package rollbar; public class MismatchedMethodSig < public static void main(String. args) < greetPerson(123); >static void greetPerson(String name) < System.out.println("Hello " + name); >>
MismatchedMethodSig.java:6: error: method greetPerson in class MismatchedMethodSig cannot be applied to given types; greetPerson(123); ^ required: String found: int reason: argument mismatch; int cannot be converted to String
1 2 3 4 5 6 7 8 9 10 11 12
package rollbar; public class MismatchedMethodSig < public static void main(String. args) < greetPerson("John"); >static void greetPerson(String name) < System.out.println("Hello " + name); >>

Rollbar in action

Can Constructors Throw Exceptions in Java
Coding Java Applications the Serverless Way

«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»

Источник

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