How to Pass Parameters to Anonymous Class

How to pass parameters to anonymous class?

Technically, no, because anonymous classes can't have constructors.

However, classes can reference variables from containing scopes. For an anonymous class these can be instance variables from the containing class(es) or local variables that are marked final.

edit: As Peter pointed out, you can also pass parameters to the constructor of the superclass of the anonymous class.

Passing parameter to anonymous class in Java

Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:

public class Seen {
public Face face;

....

this.face = new Face() { ... };
e.show(this.face);

And then,

Seen s = new Seen();
s.face.seeThis();

Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:

Approach one:

final int parameter = 5;

...(new Face() {
@Override
public void seeThis() {
System.out.println(parameter);
}
});

Approach two:

public class MyFace implements Face() {
private final int parameter;

public MyFace(int parameter) {
this.parameter = parameter;
}

@Override
public void seeThis() {
System.out.println(parameter);
}
}

Then,

...
e.show(new MyFace(10));

How to pass arguments to anonymous PHP class constructor?

Because your class require $num argument in construct, you need to pass it when you instanciate your object.


<?php

$myObject = new class(1) {
public function __construct($num)
{
echo 'Constructor Calling'.$num;
}

public function log(string $text){
return $text;
}

};

var_dump($myObject->log("Hello World"));

Will result


Constructor Calling1
string(11) "Hello World"

Why PHP asks to pass arguments to the anonymous class?

At the very end, you are instantiating a class, so, the constructor is been fired. Anonymous classes, as it's mentioned in the documentation, are useful for creating single and uniques objects, not for creating a template.

The syntax for passing params through is:

$trainerEngineClass = new class($user, $trainer) extends \App\MemoryBoost\TrainerEngine {
public function __construct($user, $trainer) {
parent::__construct($user, $trainer);
}

// Overriden abstract methods
};

Accessing outer variable in PHP 7 anonymous class

another solution could be

$outer = 'something';

$instance = new class($outer) {

private $outer;

public function __construct($outer) {
$this->outer = $outer
}

public function testing() {
var_dump($this->outer);
}
};

How to pass parameter to anonymous function

I got it to work by doing:

Sentry\configureScope(function (Sentry\State\Scope $scope) use ($username) : void {
if(!empty($username)) {
$scope->setUser(['username' => $username]);
} else if(!empty($_SESSION['username'])) {
$scope->setUser(['username' => $_SESSION['username']]);
} else {
$scope->setUser(['username' => null]);
}
});

Optional Anonymous Parameters Passing in Java

As others have suggested you can accept a variable number of Objects as function parameters. The tricky bit is unpacking that to call bar on B. I've put together an example of how you could do that using reflection:

import java.lang.reflect.Method;

public class test {
static class A {
private final Class cl;
A(Class cl) {
this.cl = cl;
}
void foo(Object ... params) throws Exception {
Object obj = cl.newInstance();
for (Method m : cl.getMethods()) {
if (m.getName().equals("bar")) {
try {
m.invoke(obj, params);
return;
}
catch(IllegalArgumentException ex) {} // try next overload
}
}
throw new IllegalArgumentException();
}
}

static class B {
public void bar() {
System.out.println("Got nothing");
}

public void bar(double a, double b) {
System.out.println("Got doubles");
}

public void bar(int a, int b) {
System.out.println("Got: " + a + " and " + b);
}
}

public static void main(String argv[]) throws Exception {
new A(B.class).foo(1,2);
new A(B.class).foo();
new B().bar(1,2);
new A(B.class).foo("Hello");
}
}

But as you will notice the overload resolution is far from perfect here and passing 1,2 in calls the double,double overload of bar. To work around that you'd need to sort the array of Method objects by best match to the Class of each object you are given, but that's far from trivial to the best of my knowledge.

How to pass anonymous types as parameters?

I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:

public void LogEmployees (IEnumerable<dynamic> list)
{
foreach (dynamic item in list)
{
string name = item.Name;
int id = item.Id;
}
}

Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.



Related Topics



Leave a reply



Submit