I have methods in a class
public class ReflectionClass {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public String concatenate (String a, String b, String c){
return a + b + c;
}
}
I'm trying to call these methods through reflection. All I have in hand are - the method name and the parameters. Is there a way to pass the parameters into the Method.Invoke() method dynamically based on the number/type of parameters I have in hand?
As you can see in the docs public Object invoke(Object obj, Object... args) takes a varargs argument - so you can simply pass an array of arguments there.
You need to create an instance, get the methods, get the parameters, check the parameters by checking the type and how many... then call invoke depending of what
Example:
public static void main(String[] args) throws Exception {
Class<?> cls = Class.forName("com.ReflectionClass");
Object obj = cls.newInstance();
for (Method m : cls.getDeclaredMethods()) {
if (m.getParameterCount() == 3 && Arrays.asList(m.getParameterTypes()).contains(String.class)) {
String a = "A";
String b = "B";
String c = "C";
Object returnVal = m.invoke(obj, a, b, c);
System.out.println((String) returnVal);
} else if (m.getParameterCount() == 2 && Arrays.asList(m.getParameterTypes()).contains(int.class)) {
int a = 5;
int b = 3;
Object returnVal = m.invoke(obj, a, b);
System.out.println(returnVal);
} else if (m.getParameterCount() == 3 && Arrays.asList(m.getParameterTypes()).contains(int.class)) {
int a = 5;
int b = 3;
int c = 3;
Object returnVal = m.invoke(obj, a, b, c);
System.out.println(returnVal);
}
}
}
Related
So my issue is that I cannot use my global variables (a,b,c) in my arguments. I need to be able to use them in my boolean function and double function. What am I doing wrong? How can I fix this?
public class triareamain extends javax.swing.JFrame {
double a, b, c;
public void DisplayError() {
side1input.setText("Error");
side2input.setText("Type");
side3input.setText("+ Integers");
}
public double areaCal(double a, double b, double c) {
double s = (a + b + c) / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
public static boolean isValid(double a, double b, double c) {
if (a > b + c || b > a + c || c > a + b) {
return true;
} else {
return false;
}
}
private void calculatebuttonActionPerformed(java.awt.event.ActionEvent evt) {
try {
a = Double.valueOf(side1input.getText());
b = Double.valueOf(side2input.getText());
c = Double.valueOf(side3input.getText());
boolean area = isValid();
if (area == false) {
double finalarea = areaCal();
} else {
DisplayError();
}
} catch (NumberFormatException e) {
side1input.setText("Error");
side2input.setText("Type");
side3input.setText("+ Integers");
}
a, b, and c are not global variables. Java doesn't have that concept. They are fields of class triareamain.
However you also created parameters of the same name, so those names are shadowing the fields.
If you wanted the areaCal() method to use the fields directly, remove the parameters:
public double areaCal() {
If you want the method to use the parameters, then pass values in the call:
double finalarea = areaCal(a, b, c);
If you keep the parameters, I highly recommend that you rename either the fields or the parameters. Shadowing of variable names is very confusing to the programmer, and will in high probability be the cause of bugs.
I am writing code in Java which has multiple methods and these methods have multiple variables. I want the other methods to access the variables of another method using actual and formal parameters. How can I do it?
I am pasting an example of the problem I'm facing.
Error : variable is not defined.
Code
public class example {
public void addition() {
int a = 0;
int b = 10;
int c = a + b;
}
public void result() {
System.out.println("The result for the above addition is" + c);
}
}
IM GETTING AN ERROR SAYING VARIABLE IS NOT DEFINED
You should declare c as global variable
public class Example {
int c;
public void addition() {
int a = 0;
int b = 10;
c = a + b;
}
public void result() {
System.out.println("The result for the above addition is " + c);
}
public static void main(String[] args) {
Example e = new Example();
e.addition();
e.result();
}
}
well, your java syntax is quite wrong... if you need to do an addition, you can do as follows:
public class Addition {
public static int addition(int a, int b)
{
int c= a + b;
return c;
}
public static void main(String[] args) {
int a = 1;
int b = 10;
int c = addition(a,b);
System.out.println("The result for the above addition is " + c);
}
}
where addition function does add a + b and return the result to your main method.
I have that following java code:
public class HelloWorld
{
static Baumhaus bauHaus(int hoehe, int breite)
{
Baumhaus b = new Baumhaus();
b.hoehe = hoehe;
b.breite = breite;
return b;
}
static Baumhaus machBreiter(Baumhaus b)
{
Baumhaus bb = new Baumhaus();
bb.hoehe = b.hoehe;
bb.breite = b.breite + 1;
return bb;
}
static Baumhaus machHoeher(Baumhaus b)
{
b.hoehe++;
return b;
}
public static void main(String[] args)
{
Baumhaus b = bauHaus(2, 3);
Baumhaus c = machBreiter(b);
c.nachbar = b;
Baumhaus d = machHoeher(b);
d.nachbar = b;
++c.hoehe;
Baumhaus e = machHoeher(b);
e.nachbar = c;
e.breite = b.breite - 1; // WHY DOES b.breite GETS DECREASED BY 1 ???
c.hoehe++;
c.breite -= 2;
boolean bUndCBenachbart = (b.nachbar == c || c.nachbar == b);
}
}
class Baumhaus
{
public int hoehe;
public int breite;
public Baumhaus nachbar;
public int nummer = ++naechsteNummer;
static int naechsteNummer = 0;
}
See the commented line ( e.breite = b.breite - 1; )
I can't understand, why the value of the variable b.breite gets changed. I'm reading a documentation about Object Oriented Programming (Java) but I am still scratching my head. Please help me
Note: I don't know how to describe my problem to google, so I couldn't find any solutions about my question. I'm sorry if duplicate
Thanks in advance :)
Because e == b.
e is defined as Baumhaus e = machHoeher(b); and
static Baumhaus machHoeher(Baumhaus b)
{
b.hoehe++;
return b;
}
in java assigning object will not create distinct copies of them.
the method :
static Baumhaus machHoeher(Baumhaus b) {
b.hoehe++;
return b;
}
returns the the same object it recives as a parameter,
so in the code line
Baumhaus e = machHoeher(b);
e object is a reference of b, decreasing e will also decrease b
The issue is that you are returning the same object in the machHoeher function. the function is returning the same object that was passed in. So you have two variables (e and b) pointing to the same object in memory.
In machBreiter, you are creating a new object, incrementing the breite, then returning the new object.
You should do the same in machHoeher:
Create New object
Inrement the hoehe
return the new object.
This will make sure that when you do e.breite = b.breite - 1, e and b are separate objects and b.breite doesn't get changed.
class A {
int a, b;
A(int i, int j) {
a = i;
b = j;
}
}
class B extends A {
int c, d;
B(int i, int j) {
c = i;
d = j;
}
}
public class HelloWorld {
public static void main(String[] args) {
A aa = new A(5, 6);
B bb = new B(3, 4);
System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);
}
}
it gives error as
HelloWorld.java:9: error: constructor A in class A cannot be applied to given types;
{
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
As you class B extends class A, you somewhere have to call the constructor of the class you are extending.
As your class A does not have a constructor with no arguments, you need to explicitly call the super constructor (the constructor from class A) as the first statement inside the constructor of your class B:
B(int i, int j) {
super(i, j);
// Your code
}
If you would have a no-args constructor in A, you would not need to do this, as the no-args constructor is implicitly called if no constructor call is specified:
B(int i, int j) {
// Your code
}
Is actually doing:
B() {
super();
// Your code
}
And as you do not have A() as a constructor, you get the error.
Check this one...
JVM always looking for no argument constructor.
class A {
int a, b;
A(int i, int j) {
a = i;
b = j;
}
public A() {
// TODO Auto-generated constructor stub
}
}
class B extends A {
int c, d;
B(int i, int j) {
c = i;
d = j;
}
}
public class pivot {
public static void main(String[] args) {
A aa = new A(5, 6);
B bb = new B(3, 4);
System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);
}
}
I have a method returning an integer. My question is how to get this number
like
int d = returning value of customerperminute methods;
Thanks in advance
public int customerperminute(){
Random R = new Random();
int r = R.nextInt(4-0);
if (r==0||r==1){
return 0;
}
if (r==2){
return 1;
}
else {
return 2;
}
}
Just invoke method like this: int d = customerperminute();
suppose the class in which this method is defined is ABC and let's say customerperminuteStat, which is static method.
class ABC{
public int customerperminute(){
Random R = new Random();
int r = R.nextInt(4-0);
if (r==0||r==1){
return 0;
}
if (r==2){
return 1;
}
else {
return 2;
}
}
public static int customerperminuteStat(){
Random R = new Random();
int r = R.nextInt(4-0);
if (r==0||r==1){
return 0;
}
if (r==2){
return 1;
}
else {
return 2;
}
}
}
this is just class definition with it's methods.
To retrieve value from the function is to call the method.
*Static Method, say customerperminuteStat can be called from any type method(static/instance). But the non-static, say instance eg. customerperminute can be called from only instance methods.*
Calling
from the method of same class
int d = customerperminute();
int e = customerperminuteStat();
from the method of some other class
int d = customerperminute();
int e = customerperminuteStat();
1)Invoke it directly in non-static methods:
int value = customerperminute();
2)Invoke it in static method, add static in the method signature:
public class Test {
public static void main(String[] args) {
System.out.println(customerperminute());
}
public static int customerperminute() {
Random R = new Random();
int r = R.nextInt(4 - 0);
if (r == 0 || r == 1) {
return 0;
}
if (r == 2) {
return 1;
} else {
return 2;
}
}
}
use the following code in main() method
public static void main(String s[]){
ABC inst = new ABC(); //create instance of class which contains called method
int d = customerperminute();
}
or make customerperminute() as static & you can directly call it using class name ABC.customerperminute() if method is in different class or directly as customerperminute() if method is in same class as main() method