Implementing Simulator Using Reflection
hey my friends,
I'm working on implementing a Simulator for PIC Microcontroller which executes Assembly instructions and makes appropriate changes in Register File and Memory.
The way I execute instructions is as follows:
I have an abstract parent class called Instruction, then I made each individual instruction as separate class that extends Instruction parent class. Now I use reflection to execute each individual instruction by creating a new object of that instruction passing its parameters and then calling execute() method.
Example :
MOVE W, 0xFF
CLRF PORTA
my Java code will look like :
Class instructionClass = Class.forName("MOVE");
Instruction inst = (Instruction) instructionClass.newInstance();
inst.passParameters(String[] parms);
inst.execute();
instructionClass = Class.forName("CLRF");
inst = (Instruction) instructionClass.forName("PORTA");
inst.passParameters(String[] parms);
inst.execute();
Is there a better fast idea or I shall keep on the same way ?
Message was edited by:
HypnotiC
Message was edited by:
HypnotiC
If you know all the types of instruction you could write a method that returns
an object based on the first word of the line.public abstract class AbstractInstruction {
protected String[] paramArr;
protected void setParam(String[] line) {
paramArr = new String[line.length - 1];
System.arraycopy(line, 1, paramArr, 0, line.length - 1);
public abstract void execute();
public AbstractInstruction create(String[] line) {
AbstractInstruction ret;
if(line[0].equals("MOVE")) ret = new MoveInstruction();
// else if() etc
else ret = new ClrfInstruction();
ret.setParam(line);
return ret;
class MoveInstruction extends AbstractInstruction {
public void execute() {
// do something with paramArr
class ClrfInstruction extends AbstractInstruction {
public void execute() {
// do something else with paramArr
}
Similar Messages
-
XML document creation using reflection
Hi all,
I'm tyring to write a class which creates an XML document from objects passed in. For example, you call the add(Object) method and it takes your object, uses reflection, then outputs XML like this...
<fieldName>fieldValue<fieldName>
The only problem is that after looking through this forum I am a little concerned about the performance of my proposed solution (using reflection).
The class will be used in a batch process which processes millions of objects (to generate a whopping XML file that'll be sent on for further processing by a third party).
Is there a better way to do this than by using reflection?
This class is going to be used by multiple batch processes hence there will be lots of different object types passed (they'll also be new ones in the future that we don't even know about yet) hence my reflection choice.
Thanks,
ChrisThe only problem is that after looking through this
forum I am a little concerned about the performance of
my proposed solution (using reflection).The only way that you'll know for sure is if you try it out. Write the code, test it, then run it in a profiler to find out where the performance problems (if any) are.
Is there a better way to do this than by using
reflection?Probably not, if you want to pass any arbitrary object to it.
One possible alternative is to have "XML aware" objects: define an interface WritesXML, that defines a method toXML(). You then check to see whether the given object implements this interface, and if it does you simply call the method, otherwise you use reflection.
Another alternative, assuming that your objects follow the Bean pattern, is to create "XML-ifiers" on the fly, similar to the way an app-server handles JSPs. First time you see an object you create a class that will write it to XML, then compile this class and invoke it for all subsequent objects. This will require that you have a JDK installed on the runtime machine, that the objects follow the Bean pattern, and that the number of instances of a given class are very high.
This class is going to be used by multiple batch
processes hence there will be lots of different object
types passed (they'll also be new ones in the future
that we don't even know about yet) hence my reflection
choice.Sounds like a good reason to use reflection. -
How to use reflection to get base classes protected field
I have one base Base classes which have protected fields and public get method to get the field.
class Base
protected int proField;
public int getProField(){return proField;}
Class Derive extends base class Base
class Derive extends Base implements OtherInterface
public void funtion(){};
Now I have an instance of Derive, how can I use reflection to get the protected field inherited from Base. It seems Java Reflection only give runtime accessibility to public field and decleared field, protected-inherited field is excluded.
Thanks
Leias the last poster said, traverse up the class hierarchy.
ex:
private void doSumfinToField(String fieldName throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
Class clazz = getClass();
Field field = findFieldInClass(clazz, fieldName);
//field.doSumfin;
private Field findFieldInClass(Class clazz, String fieldName) throws NoSuchFieldException {
try { // to find the field in this class
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
// if we don't have a superclass, continue
if (clazz.getSuperclass().equals(Object.class)) {
throw e;
// check in the superclass
return findFieldInClass(clazz.getSuperclass(), fieldName);
} -
Post implementation simulation taking long time
http://forums.xilinx.com/t5/Simulation-and-Verification/2014-4-1-stuck-at-Executing-elaborate-step/td-p/638623
Actually i referred this link since my post implementation simulation takes a long time. i tried the verbose mode
WARNING: [VRFC 10-969] keyword 'unsigned' is not allowed here in this mode of verilog . this warning constantly gets didplayed is there some problem with this.
The simulation gets stuck at executing elaborate step...
How to turn off multithreading if that can be a problem as mentioned in the above thread.
Are you using $unsigned in your code? What I know is that if you don't use a negative symbol in Verilog then it is treated as unsigned. Can you check that and may be try to remove any unsigned keywords used in your code and see if that helps. Also a log of compile & elaboration would help refer: sim_1/behav
But if you can post your project archive then that would be the fastest means to check the issue and comment. We would like to fix the issue if its really a bug :) -
Problem to calling readObject(java.io.ObjectInputStream) using reflection
Hi,
I am facing the following problem
I have an Employee class its overridden the following below methods
private void readObject(java.io.ObjectInputStream inStream) {
inStream.defaultReadObject();
I am trying to call this method using reflection.
my code is like this
Class fis= Class.forName("java.io.FileInputStream");
Constructor fcons = fis.getConstructor(new Class[]{String.class});
Object fisObj = fcons.newInstance(new Object[]{"C:\\NewEmployee.ser"});
Class ois= Class.forName("java.io.ObjectInputStream");
Constructor ocons = ois.getDeclaredConstructor(new Class[]{InputStream.class});
Object oisObj = ocons.newInstance(new Object[] {fisObj});
Method readObj = aClass.getDeclaredMethod("readObject", new Class[]{ois});
readObj.setAccessible(true);
Object mapObj = readObj.invoke(employeeObj,new Object[]{oisObj});
The above code is call the readObject method, but it is failing while executing inStream.defaultReadObject() statement
I am getting the following exception
java.lang.reflect.InvocationTargetException
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:585)
at HackEmployee.reflect(HackEmployee.java:49)
at HackEmployee.main(HackEmployee.java:131)
Caused by: java.io.NotActiveException: not in call to readObject
at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:474)
at Employee.readObject(Employee.java:77)
... 6 more
can anybody help me?
~ muraliHi,
Here is the simple example.
public class Employee implements Serializable {
static final long serialVersionUID = 1L;
static final int _VERSION = 2;
private int eno;
private String empName;
private String paaword;
private void readObject(java.io.ObjectInputStream inStream)
throws IOException, ClassNotFoundException {
int version = 0;
BufferedInputStream bis = new BufferedInputStream(inStream);
bis.mark(256);
DataInputStream dis = new DataInputStream(bis);
try {
version = dis.readInt();
Debug.println(Debug.INFO, _TAG, "Loading version=" + version);
} catch(Exception e) {
dis.reset();
switch(version) {
case 0:
case 1:
inStream.defaultReadObject();
migrateDefaultEmployeeToEncryptionPassword();
break;
case _VERSION:
inStream.defaultReadObject();
break;
default:
throw new IOException("Unknown Version :" + version);
private void writeObject(ObjectOutputStream aOutputStream)
throws IOException {
aOutputStream.writeInt(_VERSION);
aOutputStream.defaultWriteObject();
Now I am writing a tool that need to read data and print all the field and values in a file.
So I am trying the same with reflecton by calling readObject(ObjectInputStream inStream).
But here I am facing the problem, it is geving java.lang.reflect.InvocationTargetException while calling migrateDefaultEmployeeToEncryptionPassword(.
Hope you got my exact scenerio.
Thanks for your replay
~ Murali -
Using reflection to get method body
Hi,
I'm just getting into this side of program and while I understand the use of reflection in oredr to obtain the constructor and method, parameters, fields etc I was wondering if its possible to grab the method body and copy it into a string.
So for example in the following class...
class MyClass
private String str;
MyClass(){}
public String MyMethod(String s)
str=s;
str=str+" was the String";
System.out.println(str);
return str;
...I need to capture just this code..
str=s;
str=str+" was the String";
System.out.println(str);
return str;
...as a string
The reason i need to do this is that I'm programming a mechanism for storing objects and their methods using JDBC.. I could use object serialisation and store as a blob, but I'm wanting to store the attributes of a class as seperate parts so I can retrieve bits of code from the database at some later time.
Thanks for any help you might give me
peace
neilYou say that you are trying to store the method body
into a database. This is to allow you to store an
object and its methods into a database. Are you trying
store the method text or its implementation (i.e class
or java). If it is the implementation then just
serialize the found method object using reflection.
WHY are you doing this ?? what about private methods,
class variables, class methods ???Hi, yes it is confusing to explain, but I'm experimenting with a new programming paradigm called AspectJ and I've only just got into Reflection. I'm creating a repository of Aspects (same as classes but with added functionality and some limitations) with JDBC and don't want to just serialise the object as a blob and so have created data tables to hold different parts of the anatomy of an Aspect and this was the only thing I was getting stuck on.
The idea is that the user is able to recall these whole aspects (or a part of them such as a method) on the fly and use them in a program. I realise that ther will be problems because these methods may have other dependencies such as the ones you explain above but its just experimental at the moment and those are the kinds of things I'm wanting to find out more.
I've seen examples of reflection for Objects but never for methods. So it is possible to capture just a method by serialisation using reflection? Any examples would be much appreciated.
Peace
Neil -
Hi !
How do I type cast classes using reflection?
I use my own classloader and load a few classes, say 'myinterface', 'myinterfaceimpl' and 'someclass' in that custom classloader.
'myinterface' class is public where as the implementation class, 'myinterfaceimpl', access is private. 'someclass' has a method whose return type is 'myinterface', and it returns an object of instance 'myinterfaceimpl' (which is an innerclass).
1. My application starts with the system classpath (where the above 3 classes are not present).
2. My classloader loads these 3 classes.
3. Using reflection, I invoke the specified method in 'someclass', whose return type is 'myinterface'.
4. Now I am unable to invoke a public method defined in the interface, since the implementation class level access is private. I get an IllegalAccessException, when I try to invoke a method in the object returned.
5. I feel it would work, if I can somehow typecast the object returned from the method invocation to the interface class and then invoke the method.
6. The same scenario works when I don't use reflection and have them in the classpath.
Any help would be greatly appreciated. I saw a few postings related to this in the forum, but I am unable to find an answer.
Best Regards,
Ramesh.4. Now I am unable to invoke a public method defined
in the interface, since the implementation class level
access is private. I get an IllegalAccessException,
when I try to invoke a method in the object returned.Private methods cannot be used to implement methods that the interface specifies to be public, as far as I know. A class that claimed to implement an interface that way should not compile.
5. I feel it would work, if I can somehow typecast the
object returned from the method invocation to the
interface class and then invoke the method.
6. The same scenario works when I don't use reflection
and have them in the classpath.Perhaps the class you have doesn't claim to implement the interface, but just happens to have methods with the same signature, although some of them are private? If that's the case then you have a design problem that should not be worked around this way. Fix the class to implement the interface properly and you won't have to deal with any of this nonsense. -
How can i get all java class names from a package using reflection?
hi,
can i get all classes name from a package using reflection or any other way?
If possible plz give the code with example.You can't, because the package doesn't have to be on the local machine. It could be ANYWHERE.
For example, via a URLClassLoader (ie from the internet) I could load a class called:
com.paperstack.NobodyExpectsTheSpanishInquisitionI haven't written it yet. But I might tomorrow. How are you going to determine if that class is in the package?
This subject comes up a lot. If you want to do something a bit like what you're asking for (but not quite) there are plenty of threads on the subject. Use google and/or the forum search facility to find them.
But the answer to your question, as you asked it, is "you can't do that". -
How to make load simulator using labview 2010
i want to ask how to make load simulator using labview?
Solved!
Go to Solution.what have you tried so far? and exactly what is it your tying to do?
Please remember to accept any solutions and give kudos, Thanks
LV 8.6.1, LV2010,LV2011SP1, FPGA, Win7 -
Calling a pkg from managed code and then using reflection to call a method from a script task
Hi we run 2012 std. I have some pretty good evidence that when I call my pkg from a .net service, a script component in that pkg fails when trying 2 use reflection to load and invoke our .net message history method. The exception is either on
the invoke or in the message history method. I suspect its in the method but will take additional steps 2 verify.
But when I run the pkg stand alone, it has no problem and the method does what it is supposed 2 do.
There r no vars passed from the service to the pkg. I wonder if its a managed to unmanaged to managed issue that the community is already aware of. If not, my apologies 4 posting this quickly.
I'll post more info here as I collect it.we have 2 theories after showing the exception trace to folks who r more adept at managed code.
the first is related to the fact that our 3rd party dlls (I think entity framework is included in these) r older versions. I don't want to discount this theory but we have some evidence already that this might not be true.
I hope I can do justice to the 2nd theory but will make it clearer and clearer as I get a better understanding. I believe this is what Arthur was saying and I applaud his instincts. They explained that .net is so "smart" that it detected
a change in namespace (ie context as Arthur said) and purposely threw an exception 2 save us from ourselves. The workarounds discussed were a bit over my head but I will continue trying to better understand it. The fact that many of the methods
we call after reflection r now merged into one assembly seemed relevant to the discussion and possible workarounds.
this link came up in their discussion and I believe the bottom line here is that by qualifying assembly names further (in config?)r, a workaround is possible.
http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx .
This link came up as well and has something to do with ILMerge and workarounds to ILMerge.
http://elegantcode.com/2011/04/02/dynamically-load-embedded-assemblies-because-ilmerge-appeared-to-be-out/ .
Finally, this link came up and seems to have something to do with embedding your dlls in one assembly without them losing their identity.
http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
I'll post more here as we muddle thru this. -
Using reflection...
Hi,
I have one class. to run that, I am calling like the following...
java -classpath ;.;\comdotebo; com.pack1.MyClass
now I want to take the reference of this class(dynamically) using reflection pakcage like the following...
Class cla = Class.forName("com.pack1.MyClass");
but to take the class reference I need to set the classpath;
so how can i set the classpath dynamically.
please give proper solution
thanks
Raja Ramesh Kumar Mhere the case is we know both the class and the class path at run time only
for ex: see the following.....
I have two files .....
1) c:\dir1\com\pack1\MyClass1.class
2) c:\dir2\com\pack2\MyClass2.class
now I want to access both the classes using reflection from ...
c:\dir3\com\pack3\MainClass.class
using reflection, we can write the following...
Class clas1 = Class.forName("com.pack1.MyClass1");
if I am taking like this, then I am getting ClassNotFoundException.
becoz, for that we have to give the proper classpath before running the program.
like.
set classpath=%classpath%;.;c:\dir1;
but my problem is here I know the the class name (for ex: com.pack1.MyClass1) and the classpath (ex: c:\dir1)
at runtime only.
so please tell me how to solve this problem
regards
Raja Ramesh Kumar -
How to create an array using reflection.
How to create an array using reflection.
I want to achive something like this,Object o;
o = (Object)(new TestClass[10]);but by use of reflection.
To create a single object is simple:Object o;
o = Class.forName("TestClass").newInstance();But how do I create an array of objects, when the class of objects is known only by name? (Can't use Object[] because even though an Object[] array can be filled with "TestClass" elements only, it Cannot be casted to a TestClass[] array)
Anybody knows?":-)
Ragnvald Barth
Software enigneerFound it!
the java.lang.reflect.Array class solves it!
Yes !!! -
How To: Use reflection to create instance of generic type?
I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
My first guess was to write the following:
Class cls = Class.forName("java.util.ArrayList<String>");
List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
Class cls = Class.forName("java.util.ArrayList");
List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
If I change the second line to
List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?Harald,
I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
List<T> list = new ArrayList<T>();
for ( ...whatever ...) {
T obj = clazz.newInstance();
// code to load from storage ...
list.add(obj);
return list;
}And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
private static Map<String, Class<? extends Base>> classMap = null;
static
Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
classMap = Collections.synchronizedMap(map);
public static Class<? extends Base> getClass(String name)
return classMap.get(name);
protected static void putClass(Class<? extends Base> cls)
classMap.put(cls.getName(), cls);
}And added a static initializer to each of my persistent classes:class Foo extends Base
static
Base.putClass(Foo.class);
}So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
Thanks again for your help,
Gary -
Working around unchecked conversions when using reflection
I think I've convinced myself that there's no way around this issue when using reflection and Generics, but here's the issue:
Suppose I've got a method that uses reflection to compare an arbitrary property in
an arbitrary pair of beans (of the same class).
public static <T> int compare(T bean0, T bean1, String prop) throws Exception {
Method m = bean0.getClass().getMethod(
"get" + prop.substring(0,1).toUpperCase() +
prop.substring(1));
Object o0 = m.invoke(bean0);
Object o1 = m.invoke(bean1);
if (o0 instanceof Comparable &&
o1 instanceof Comparable &&
(o1.getClass().isAssignableFrom(o0.getClass()) ||
o0.getClass().isAssignableFrom(o1.getClass()))) {
return ((Comparable)o0).compareTo(o1); // compiler warning
} else {
return o0.toString().compareTo(o1.toString());
}There's no way that, in general, when using reflection to invoke methods, that you can coerce the types to avoid compile-time type safety warnings. I think the above code is guarranteed not to throw a runtime ClassCastException, but there's no way to write the code so that the compiler can guarrantee it. At least that's what I think. Am I wrong?Ok it looks like you're dealing with a classloader issue. when you call that method, it is the equivelant of calling
Class.forName("Box", true, this.getClass().getClassLoader())The exception is thrown when your class's classloader cannot find the class box. try putting 'null' there
Class.forName("Box", true, null)and it will request the bootstrap classloader to load the class. just make sure you have permission :
If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader. (copied from the API) -
Creating objects using reflection
Hi,
I need to construct a new instance using reflection and passing parameters. If the parameters are of primitive type ex. int, how can I pass them in the Class[] type of objectInteger.TYPE, etc. are Class objects that represent the types of the primitives.
Maybe you are looking for
-
How to install Maverick on new HDD before replacing current Without Original OS X Disk
Hello Community, I am looking for some advice / help. I have a Mac mini Early 2009, I want to replace 120GB Drive with a new larger drive, how do I setup Maverick on the new drive before swapping out. I do not have my original OS X Disk, I have purch
-
After i updated my i phone my screen has not been working right
ok so has any one else has this problem my screen is very dark almost to the point where i can not see it i have to hold it at an angle just to see the screen i tried to call apple but they were already closed i am going to try and call tomorrow but
-
Insert and Updateusing Bulk Operations
Hi, We are on 10g (10.2.0.5.0). We have a batch that will insert/update ~30mm records in each load. The logic is usual if a record exists in target table update it if not insert. Considering the amount of data to be loaded simple For loop will be ver
-
How can I tell apple that mails in my ipad junk folder are NOT spam, and how to avoid this in the future. It is more than enojing not to get electronic invoices and then have to pay extra cost for delayed payment - can I send these extra invoice to a
-
How to switch on austrian store, How to switch on austrian store
How to switch on austrian store, How to switch on austrian store