I have a code that uses Field built in function in java and i could not find a way to replace it in c++ the code is shown below,
import java.lang.reflect.Field;
public class ParameterValue {
public String objectPath;
public Object objectReference;
public String fieldPath;
public String fieldPathNoCase;
public Field field;
public double value;
public ParameterValue(String path, ObjectTree tree, Field fieldInfo) {
objectPath = path;
objectReference = tree.getObject(path);
field = fieldInfo;
fieldPath = objectPath + "." + field.getName();
fieldPathNoCase = fieldPath.toLowerCase();
read();
}
public int getPrecision() {
if (field.getType().getName() == "float" || field.getType().getName() == "double")
return 2;
else
return 0;
}
public double getPrecisionMultiplier() {
return Math.pow(10, getPrecision());
}
public void read() {
String type = field.getType().getName();
try {
if (type.equals("double"))
value = field.getDouble(objectReference);
else if (type.equals("float"))
value = field.getFloat(objectReference);
else if (type.equals("int"))
value = field.getInt(objectReference);
else if (type.equals("byte"))
value = field.getByte(objectReference);
else
throw new RuntimeException();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
value = Math.round(value * getPrecisionMultiplier()) / getPrecisionMultiplier();
}
public void write() {
String type = field.getType().getName();
try {
if (type.equals("double"))
field.setDouble(objectReference, value);
else if (type.equals("float"))
field.setFloat(objectReference, (float)value);
else if (type.equals("int"))
field.setInt(objectReference, (int)Math.round(value));
else if (type.equals("byte"))
field.setByte(objectReference, (byte)Math.round(value));
else
throw new RuntimeException();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void rebind(ObjectTree tree) {
objectReference = tree.getObject(objectPath);
}
}
What i have understood from the code is that i need to find a class that can convert the value in it to Double, Float,etc. I have looked for something that can do this but i was not able to do so.
reference of the code:
https://www.programcreek.com/java-api-examples/index.php?source_dir=SecugenPlugin-master/src/sourceafis/simple/Fingerprint.java#
As per my knowledge there is no equivalent class in C++. Now for your requirement first you list out what are all a java.lang.reflect.Field class provides in java. Once you listed all the utility methods, just sort list all methods that you really requires in your C++ application. Once done you do create a C++ class with the same name and methods types and implement the logic by yourself if possible.
Related
i've a rather complex problem. I'am currently developing a a little groovy based script language for an ERP System. The functions and syntax of "my" script language are based on the already existing old FO language which is used by the erp system.
Therefore: I'am getting values from the ERP with calls like h.fieldname, where h the currently selected dataset is and fieldname the name of the field I want my field value from.
I get the field value e.g. of type String. What I now want is to extend these strings I retrieve with a few functions, which are based on the "old" syntax.
// some samples
// get last 3 characters
h.fieldname >> 3
// get first 4 characters
h.fieldname << 4
// should still work even if h.fieldname, returns something which extends String but is not a String
assert h.fieldname == "Foo"
UPDATE
I tried to make use of the answer of #daggett, here my approach:
public abstract class BaseScript extends Script implements GroovyObject {
#Override
public Object run() {
Object o = null;
try {
final ExpandoMetaClass metaClass = new ExpandoMetaClass(String.class, false, true);
//Closure c = { int x-> delegate[-x..-1] };
//ClosureMetaMethod foo = new ClosureMetaMethod​("rightShift ", c , doCall);
metaClass.initialize();
o = runCode();
} catch (Exception e) {
this.onerror(e);
} finally {
this.always();
}
return o;
}
public abstract Object runCode();
public Object always() {
return null;
}
public Object onerror(Object ex) {
if (ex instanceof Exception) {
Exception e = (Exception) ex;
e.printStackTrace();
}
return null;
}
}
But honestly i've no idea how to implement it and I also can't find any example.
UPDATE 2 and solution
Based on the answer of #daggett.
package groovy.runtime.metaclass.java.lang;
import groovy.lang.DelegatingMetaClass;
import groovy.lang.MetaClass;
public class StringMetaClass extends DelegatingMetaClass {
public StringMetaClass(Class<?> theClass) {
super(theClass);
}
public StringMetaClass(MetaClass metaClass) {
super(metaClass);
}
#Override
public Object invokeMethod(Object object, String name, Object[] args) {
// implementiert "test" >> 3
if (name.equals("rightShift")) {
if (args.length == 1) {
if (args[0] instanceof Integer) {
String str = object.toString();
int x = ((Integer) args[0]).intValue();
if (str.length() > x) {
return str.substring(str.length() - x);
}
return str;
} else {
throw new IllegalArgumentException("wrong argument type, should be integer");
}
} else {
throw new IllegalArgumentException("too many arguments");
}
}
// implementiert "test" << 3
if (name.equals("leftShift")) {
if (args.length == 1) {
if (args[0] instanceof Integer) {
String str = object.toString();
int x = ((Integer) args[0]).intValue();
if (str.length() > x) {
return str.substring(0,x);
}
return str;
} else {
throw new IllegalArgumentException("wrong argument type, should be integer");
}
} else {
throw new IllegalArgumentException("too many arguments");
}
}
else {
return super.invokeMethod(object, name, args);
}
}
}
you can't extend string class because it's final, however in groovy you can add new methods to string class with help of metaclass
String.metaClass.rightShift = { int x-> delegate[-x..-1] }
"1234567890" >> 3
returns
890
in the same way implement the method leftShift for <<
the last request (assert s1==s2) is not relevant because String is a final class (not extendable)
i have the code like this when i create it like this
public final class PhpArray extends AbstractMap
{
private TreeMap t;
private HashMap m;
public PhpArray() {
this.t = new TreeMap(Request.PHP_ARRAY_KEY_COMPARATOR);
this.m = null;
}
#Override
public Object put(final Object key, final Object value) {
if (this.m != null) {
return this.m.put(key, value);
}
try {
return this.t.put(key, value);
}
catch (ClassCastException e) {
this.m = new HashMap(this.t);
this.t = null;
return this.m.put(key, value);
}
}
#Override
public Set entrySet() {
if (this.t != null) {
return this.t.entrySet();
}
return this.m.entrySet();
}
public int arraySize() {
if (this.t == null) {
throw new IllegalArgumentException("The passed PHP \"array\" is not a sequence but a dictionary");
}
if (this.t.size() == 0) {
return 0;
}
return 1 + this.t.lastKey();
}
}
but when i update my project i got error in the code
return 1 + this.t.lastKey();
the error is an arguments + is undefined.. why like that ? and how to fix the problem ?
TreeMap is a generic class but in the code in your question you have used it without type parameters. This means that this line of your code:
private TreeMap t;
is essentially this:
private TreeMap<Object, Object> t;
In other words t.lastKey() returns an Object and the operator + can't be used with Object because an Object is not a number.
Perhaps you meant to call method size() rather than method lastKey()?
Perhaps this tutorial will help?
For this assignment, I write a program, which will calculate the results of Reverse Polish expressions that are provided by the user.
I must use a linked list to maintain the stack for this program (array implementations of the stack will not receive full credit).
I must handle the following situations (errors):
Too many operators (+ - / *)
Too many operands (doubles)
Division by zero
The program will take in a Polish expression that separates the operators and operands by a single space, and terminates the expression with an equals sign.
The program will continue to take and evaluate expressions until the user enters a zero (0) on a line by itself followed by a new line.
my sample output should show the handling of all the error conditions as well as make use of all of the operators. But when I execute the program it says
Error: Main method not found in class program1.Program1, please define the main method as:
public static void main(String[] args)
Java Result: 1
I have no idea how to call linked list without array implementations. Also
RefObject class and TryparseHelper are below in the same package. tnx
package program1;
import java.util.*;
import java.lang.IllegalStateException;
public class Program1 {
public class Node<T>
{
public T Data;
public Node<T> Next;
}
public class Stack<T>
{
private Node<T> top = null;
public final void Push(T value)
{
top = new Node<T>();
top.Data = value;
top.Next = top;
}
public final T Pop()
{
if (top == null)
{
throw new IllegalStateException("Cannot pop if the stack is empty.");
}
T topValue = top.Data;
top = top.Next;
return topValue;
}
public final boolean IsEmpty()
{
return top == null;
}
public final void Clear()
{
top = null;
}
}
public class ReversePolishCalculator
{
public final void Calculator()
{
String expression = "";
while (!expression.equals("0"))
{
System.out.print("Enter expression: ");
expression = new Scanner(System.in).nextLine();
try
{
System.out.println(" = " + Calculate(expression));
}
catch (RuntimeException ex)
{
System.err.println(ex.getMessage());
}
}
}
private Stack<Double> stack = new Stack<Double>();
private double Calculate(String expression)
{
double result = 0.0;
stack.Clear();
String[] tokens = expression.split("[ ]", -1);
for (String token : tokens)
{
double value = 0;
RefObject<Double> tempRef_value = new RefObject<Double>(value);
if (TryParseHelper.tryParseDouble(token, tempRef_value))
{
value = tempRef_value.argValue;
stack.Push(value);
}
else
{
value = tempRef_value.argValue;
DoOperation(token);
}
}
if (!stack.IsEmpty())
{
result = stack.Pop();
}
if (!stack.IsEmpty())
{
throw new IllegalStateException("Too many operands.");
}
return result;
}
private void DoOperation(String token)
{
if (stack.IsEmpty())
{
throw new IllegalStateException("Too many operators.");
}
double rhs = stack.Pop();
if (stack.IsEmpty())
{
throw new IllegalStateException("Too many operators.");
}
double lhs = stack.Pop();
switch (token)
{
case "+":
stack.Push(lhs + rhs);
break;
case "-":
stack.Push(lhs - rhs);
break;
case "*":
stack.Push(lhs * rhs);
break;
case "/":
if (rhs == 0.0)
{
throw new IllegalStateException("Divide by zero.");
}
stack.Push(lhs / rhs);
break;
default:
throw new IllegalStateException("Unexpected operator: " + token);
}
}
}
}
package program1; TryParseHelper
/**
*
* #author David
*/
public final class TryParseHelper
{
public static boolean tryParseInt(String s, RefObject<Integer> result)
{
try
{
result.argValue = Integer.parseInt(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseShort(String s, RefObject<Short> result)
{
try
{
result.argValue = Short.parseShort(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseLong(String s, RefObject<Long> result)
{
try
{
result.argValue = Long.parseLong(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseByte(String s, RefObject<Byte> result)
{
try
{
result.argValue = Byte.parseByte(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseDouble(String s, RefObject<Double> result)
{
try
{
result.argValue = Double.parseDouble(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseFloat(String s, RefObject<Float> result)
{
try
{
result.argValue = Float.parseFloat(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseBoolean(String s, RefObject<Boolean> result)
{
try
{
result.argValue = Boolean.parseBoolean(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
}
package program1; RefObj
/**
*
* #author David
*/
public final class RefObject<T>
{
public T argValue;
public RefObject(T refArg)
{
argValue = refArg;
}
}
As the error message you've pasted says: To run your program, add to Program1 class a method with this signature public static void main(String[] args). Write in it the code you want to run, e.g., System.out.println("hi"); or whatever.
Update: As I understood from your comment, it seems like your problem is trying to call a non-static method Calculator() from main(...). First, you need a background on class vs object and static vs non-static.
A class is a template or a blueprint. An object is an instantiation of that blueprint. For example, a description of a car is a class, any car is an object. Another example is your Stack class and the Stack<Double> stack = new Stack<Double>() object you've used to calculate an expression.
When you call pop() it needs a specific stack to run on. A specific object. For example, you could have 2 stacks at the same time, and calling pop() on one of them shouldn't affect the other. That's why the method pop() is non-static.
Now, let's think of the Program1 class: Are you really thinking of creating multiple program1 and running them/calling their methods in your code? And would each program1 have a different state from the other? Each stack could have different contents at any time, but program1 doesn't really have any content or state.
When you have a method that doesn't depend on any specific object or a particular state, you mark it as static. For example, a method that adds 2 numbers should be static. Same goes for your Calculator() method.
So, back to your question, to call non-static method Calculator() from main(...), you'll either have to:
(1) convert Calculator() into a static method. You need to ask yourself "Is this method related only to a specific instance, a specific object?". For example, the pop() method of Stack is very related to a certain stack object. If you call it on 2 stack objects, it'll give different results. That's why it should be a non-static method, i.e., a method that depends on a particular instance.
However, Calculator() seems like a method that doesn't really depend on anything else. The fact that it uses a member variable called stack is accidental. You can move the stack variable inside Calculator(). Or you could just make stack static as well.
(2) You could, although it wouldn't make much sense, create an instance of Program1 then call Calculator() on it.
I know the difference between class and object, and static and non-static, can be confusing in the beginning. Read more on it, you'll get comfortable with it with time.
For the without-arrays question: If I understand correctly, you have a problem with the array in main(String[] args). The array here is a must for the program to run and is not related to the stack's implementation. So, I don't expect you teacher to mind having it.
Finally, note that the code, I think, has some problems so don't expect it to run from the first time. And that's absolutely normal, and you'll need to know how to trace a code. Good luck!
I have this code in Modula-2,
PROCEDURE Prune(typeExp: TypeExp): TypeExp;
BEGIN
CASE typeExp.^class OF
| VarType:
IF typeExp^.instance = NIL THEN
RETURN typeExp;
ELSE
typeExp^.instance = Prune(typeExp^.instance);
RETURN typeExp^.instance;
END;
| OperType: RETURN typeExp;
END;
END Prune;
I have several problems when I try to convert this code into java. I can create an instance and judge if its instance is null and then choose what to return. But I don't really know what to do with the case 2, which is the instance might be a new Opentype(); because only one value can be returned in this case.
public TypeExp Prune(TypeExp typeExp){
TypeExp r = new VarType();
if (r.instance == null) {
return r;
}
else {
r.instance = Prune(r.instance);
return r.instance;
}
}
The second issue is I don't think I can call the function Prune() inside itself, so what can I do? Thanks in advance.
I dont really know Modula-2, but it might be something like this:
public TypeExp Prune(TypeExp typeExp) {
if (typeExp instanceof VarType) {
if (typeExp.instance == null) {
return typeExp;
}
else {
typeExp.instance = Prune(typeExp.instance);
return typeExp.instance;
}
} else if (typeExp instanceof OperType) {
return typeExp;
}
//if typeExp is not an instance of VarType or OperType
return null;
}
The Modula code does not return in all code paths. Thats not possible in Java. I inserted return null in those cases. Thats probably wrong for your application though.
Below example not same as your func, but I think you can modify to your needs. It hides your return types behind Type class => you can return objects of two classes.
Main
package com.type;
public class Main {
public static void main(String[] args) {
Type first = new FirstType();
Type second = new SecondType();
System.out.println(func(first).getTypeName());
System.out.println(func(first).getTypeName());
System.out.println(func(second).getTypeName());
}
public static Type func(Type type) {
if(type instanceof FirstType) {
type.setTypeName("First");
} else {
type.setTypeName("Second");
// something here
}
return type;
}
}
Type
package com.type;
public class Type {
private String typeName;
public Type() {}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
FirstType
package com.type;
public class FirstType extends Type {
}
SecondType
package com.type;
public class SecondType extends Type {
}
This question already has answers here:
Can Java store methods in arrays?
(5 answers)
Closed 6 months ago.
I dont know if its posible but can I store methods or functions in an array? I know Multi dimensional array now and use it to store many arrays as i want. What i would like to do now is to store the methods or functions I create in a certain class. Because i want to store all of my functions to a certain class then call it if i want using loop. And to make my coding cleaner and easy to understand.
Example:
public String[] getDesiredFunction = {getName(),getLastname(),getMiddle()};
for(int i = 0;i<3;i++){
if(i == 1){
getDesiredFunction[i];
}
}
like that?
Is it posible?
You can't do exactly what you want, but can do something similar using an interface:
interface Function {
public void run();
}
class GetNameFunction implements Function {
public void run() {
//do stuff
}
}
...
And then you can write like this:
Function[] functions = {new GetNameFunction()};
for(int i = 0; i < functions.length; i++){
functions[i].run();
}
}
Java 6 does not have first-order functions, but you can use a functional object pattern:
interface NullaryFunction< B > {
B f();
}
public class Example {
private final Map< String, NullaryFunction< String > > mFuncs = new HashMap< String, NullaryFunction< String > >() { {
put( "getName", fncGetName );
put( "getLastname", fncGetLastname );
put( "getMiddle", fncGetMiddle );
} };
public String getName() { /* ... */ }
private NullaryFunction< String > fncGetName = new NullaryFunction< String >() {
#Override String f() { return getName(); }
};
public String getMiddle() { /* ... */ }
private NullaryFunction< String > fncGetMiddle = new NullaryFunction< String >() {
#Override String f() { return getMiddle(); }
};
public String getLastname() { /* ... */ }
private NullaryFunction< String > fncGetLastname = new NullaryFunction< String >() {
#Override String f() { return getLastname(); }
};
public String runAFunction( String strName ) {
return mFuncs.get(strName).f();
}
}
Java is not well suited for your use case. It is possible do with reflection.
As a starting point you could look into the reflection trail or see the related stackoverflow question.
You can store object instance and method name as string, using reflection can invoke this method like this:
public class Test {
public void sayHello(){
System.out.println("hello");
}
/**
* #param args
*/
public static void main(String[] args) {
Test test = new Test();
String methodName = "sayHello";
try {
Method m = test.getClass().getMethod(methodName, null);
m.invoke(test, null);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
You need refer java refection
The way you stated in the question won't work. As a alternative you could do it like:
public String[] getDesiredFunction = {getName(),getLastname(),getMiddle()};
for(int i = 0;i<3;i++){
if(getDesiredFunction[i].equals("getName()")){
getName();
}
}