passing method as parameter and getting error: java.lang.NoSuchMethodException: [duplicate] - java

This question already has answers here:
Java: NoSuchMethodException when method clearly exists
(4 answers)
Closed 9 years ago.
I am getting error: java.lang.NoSuchMethodException:
here is my code
public class ManageEnrollmentTest {
#Test
public void Test_Filter_By_Active() throws Exception{
assertTrue("Log in failed", Helper.LoginTest());
assertTrue("Activation failed", fitlerResults("Active"));
}
private Boolean fitlerResults(String dS){
Boolean isOk = false;
try{
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("$('#dType').val('36').change().trigger(\"liszt:updated\");;");
WebElement findButton = driver.findElement(By.id("findDealersBtn"));
findButton.click();
Method method = ManageEnrollmentTest.class.getMethod("verifyActive"); //////// Error
isOk = loadEnrollmentTablePageByPageAndVerify(method);
}
catch(Exception e){
e.printStackTrace();
isOk = false;
}
return isOk;
}
private Boolean loadEnrollmentTablePageByPageAndVerify(Method method){
return (Boolean)method.invoke(this);
}
//browse throw all dealers that are currently on page
private Boolean verifyActive(){
....
....
return isOk;
}
}

Your method is private but getMethod() only returns public method.You need to use getDeclaredMethod().
getMethod() - Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

Related

Java consumer with return [duplicate]

This question already has answers here:
Why does a Java method reference with return type match the Consumer interface?
(2 answers)
Why doesn't for-each method in java not throw an exception when a Function type argument is passed instead of Consumer? [duplicate]
(3 answers)
Closed 4 years ago.
I don't understand why this code is working:
class Resource {
private Resource() {
System.out.println("created...");
}
public Resource op1() {
System.out.println("op1");
return this;
}
public Resource op2() {
System.out.println("op2");
return this;
}
private void close() {
System.out.println("clean up...");
}
public static void use(Consumer<Resource> block) {
Resource resource = new Resource();
try {
block.accept(resource);
}
finally {
resource.close();
}
}
}
// method call
public class App
{
public static void main( String[] args )
{
Consumer<Resource> block = resource -> resource.op1().op2(); //here
Resource.use(block);
}
}
Consumer should accept one parameter and return void. But in this example Consumer take one parameter(resource) and return this parameter. Why it is working although I return resource instance instead of void?
Your Consumer<Resource> block = resource -> resource.op1().op2(); is equivalent to:
Consumer<Resource> block = new Consumer<Resource>() {
#Override
public void accept(Resource resource) {
resource.op1().op2(); // there is no return statement
}
};

I am facing a class cast exception, from java.lang.Double to java.lang.Integer [duplicate]

This question already has answers here:
Cast Double to Integer in Java
(19 answers)
Closed 5 years ago.
I am writing a JUnit test case for a method that has a getValue() method which returns an Object, the getValue() returns the value I pass inside setValue() and In this case when I pass a double value to setValue() it gives a class cast exception. I am not able to figure out how to fix this.
This is the if condition I am testing,
Public class ImageToolsMemento
{
public static final int FREEROTATION=3;
private double _freeRotation;
public void combine(ImageToolsMemento obj) //test method
{
if(((Integer)(obj.getValue(FREEROTATION))).intValue() != 0)//line 224
_freeRotation = ((Integer)(obj.getValue(FREEROTATION))).intValue();
}
public Object getValue(int type)
{
Object ret;
switch(type)
{
case FREEROTATION:
default:
ret = null;
}
return ret;
}
public void setValue(double value, int type)
{
switch(type)
{
case FREEROTATION:
_windowPanelMemento.setValue(value, type);
break;
default:
//"default case"
break;
}
}
}
Test case
public class ImageToolsMementoTest
{
#InjectMocks
ImageToolsMemento imageToolsMemento;
#Before
public void setUp() throws Exception
{
imageToolsMemento=new ImageToolsMemento();
}
#Test
public void testCombine()
{
imageToolsMemento.setValue(1.3, ImageToolsMemento.FREEROTATION);
imageToolsMemento.combine(imageToolsMemento);//calling test method, line 553
double _freeRotation=Whitebox.getInternalState(imageToolsMemento, "_freeRotation");
assertEquals(1.3,_freeRotation,0.0);
}
}
Stack trace
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
at com.toolboxmemento.ImageToolsMemento.combine(ImageToolsMemento.java:224)
at com.toolboxmemento.test1.ImageToolsMementoTest.testCombine(ImageToolsMementoTest.java:553)
Can anyone please help me out with this problem
P.S I cannot change the implementation
In java you cannot cast java.lang.Double to java.lang.Integer. Your error comes on line :
if(((Integer)(obj.getValue(FREEROTATION))).intValue() != 0)//line 224
Instead of cast you can use intValue method of Double class:
if(((Double)obj.getValue(FREEROTATION)).intValue() != 0)//line 224
You need to perform explicit typecasting because double will not stored in int type implicitly.You can do this by :
int i = (int) d;

Non-static method referenced from a static context [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 8 years ago.
I have two errors both the same and they follow below:
class FBox {//...}
class FBPlayer
{
//Initialized instances
FBox game = new FBox();
**FBPillar pillar = new FBPillar();**
**FBObjects objects = new FBObjects();**
//Lots o Properties...
public boolean get_Alive() { return this.b_PlayerAlive; }
public void set_Alive(boolean alive) { this.b_PlayerAlive = alive; }
//My Error ridden Method
public void checkCollision()
{
if(get_YPos() >= **objects**.get_Ground())
^My Error was incorrect name for my instance
{
set_Alive(false);
}
else if(get_Bounds().intersects(**pillar**.get_Bounds()))
^My Error was incorrect name for my instance
{
set_Alive(false);
}
}
class FBPillar
{
public int get_Bounds() {return 'the variable'; }
}
class FBObjects
{
public int get_Ground() {return 'the variable'; }
}
The error is in the if statement as well as the else if statement
When i run it it returns the error:
FBox.java:178: error: non-static method get_Bounds() cannot be referenced from a static context
else if(get_Bounds().intersects(**FBPillar**.get_Bounds()))
The same error for the if statement but with FBObjects.get_Ground())
^
Whose bounds are you talking about? You probably mean
if (get_Bounds().intersects(pillar.get_Bounds())) {
…
}
I'd also add that
FBPlayer player = new FBPlayer();
means that a player contains a player, which is probably isn't what you intended.

Get generic type T in Java? [duplicate]

This question already has answers here:
Get generic type of class at runtime
(30 answers)
Closed 8 years ago.
I have this class:
public class ActorFixture<T>
{
public T actor;
public String fixture;
public ActorFixture() {}
public ActorFixture(T actor, String fixture)
{
this.actor = actor;
this.fixture = fixture;
}
public void setFixture(Fixture fa, Fixture fb)
{
Class<T> type;
if (type.isInstance(fa))
{
actor = type.cast(fa.getBody().getUserData());
fixture = (String)fa.getUserData();
}
else if (type.isInstance(fb))
{
actor = type.cast(fb.getBody().getUserData());
fixture = (String)fb.getUserData();
}
}
}
But I get a warning on 'type' because it's not initialized.
What's the correct way to check the type?
Try this:
Class<T> type = (Class<T>) this.actor.getClass();

Error: 'void' type not allowed here [duplicate]

This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I'm learning to use classes and part of my assignment is to make this Car class. I'm getting an error on line 6 where I attempt to print of the results of the methods within the class. I think this means that I'm attempting to print something that doesn't exist and I suspect it's the mileage method. I tried changing it to return miles, but that didn't work either. Any ideas?
public class TestCar {
public static final void main(String args[]) {
Car c = new Car ();
c.moveForward(4);
System.out.println ("The car went" + c.mileage() + "miles."); // <-- L6
}
}
class Car {
public int miles = 2000;
public void moveForward(int mf) {
if (miles != 2000) {
miles += mf;
}
}
public void mileage() {
System.out.print(miles);
}
}
The error message is telling you exactly what is wrong -- you're trying to extract a result from a method that does not return a result.
Instead, have the mileage() method return a String, not print out a String.
public String mileage() {
return String.valueOf(miles);
}
Myself, I'd make this a getter method, and instead would do:
public int getMiles() {
return miles;
}
Car.mileage() is void, i.e., does not return anything. It needs to return something, like in:
public int mileage() {
return miles;
}

Categories