need help translating a code snippet from java to C# equivalent - java

Here's the code snippet I'd like to translate from Java to C#. I'm not sure what's causing the error but I've never used ArrayLists and vectors before. Thanks in advance!!
//Java class definitions, constructors, fields, methods etc here.
//sphbasis is a Vector object.
public SphericalHarmonicDecomposition[] getSphericalHarmonicBasis() {
return (SphericalHarmonicDecomposition[])(sphbasislist.toArray(
new SphericalHarmonicDecomposition[sphbasislist.size()]));
}
I've tried doing the following in C#:
//C# class definitions, constructors, fields, methods etc here.
//sphbasis is a ArrayList object.
public SphericalHarmonicDecomposition[] getSphericalHarmonicBasis() {
return (SphericalHarmonicDecomposition[])(sphbasislist.ToArray(
new SphericalHarmonicDecomposition[sphbasislist.Count]));
}
I get the following errors. I'm using Mono and Xamarin studio on a mac.
Error CS1502: The best overloaded method match for
`System.Collections.ArrayList.ToArray(System.Type)'
has some invalid arguments (CS1502) (projectx)
and
Error CS1503: Argument `#1' cannot convert
`matdcal.engine.model.SphericalHarmonicDecomposition[]' expression
to type `System.Type' (CS1503) (projectx)

Please try the following. In Java you need to pass an array to the toArray method, but that's not correct in C# (.NET).
//C# class definitions, constructors, fields, methods etc here.
//sphbasis is a ArrayList object.
public SphericalHarmonicDecomposition[] getSphericalHarmonicBasis() {
return (SphericalHarmonicDecomposition[])(sphbasislist.ToArray());
}
References
Java ArrayList.toArray
C# List.ToArray

Related

Is it possible to use JNA/JNI to access native COM/DirectX API methods?

I'm trying to call this native Windows method using JNA:
HRESULT WINAPI DirectSoundCreate(LPGUID lpGuid, LPDIRECTSOUND* ppDS, LPUNKNOWN pUnkOuter );
But I'm really struggling with understanding what I should use as parameters on the Java side of things. With JNA you're supposed to create Java classes matching the native C structs, and I have done so succesfully with other parts of the WinAPI.
From what I've (I think) understood so far the LPDIRECTSOUND is a typedef to a "Long pointer to a DirectSound struct" and LPUNKNOWN is a typedef "Long pointer to an Unknown"?
I've found the native structs IDirectSound and IUnknown in DSound.h. Am I supposed to use these? I can't find a specification on what these structs contain, however, so when I try to mirror them as empty classes extending Structure on the Java side I get
IllegalArgumentException: Structure class se.abjorklund.win32.jna.dsound.IDirectSound has unknown or zero size (ensure all fields are public)
So that obviously doesn't work. I'm guessing I'm missing something fundamental here, maybe it has something to do with the COM/Direct API that I don't understand, and answers like "go read up" are cool, as long as I can get pointers as to what to read!
Below is a working snippet of the C program I'm trying to port to Java using JNA.
LPDIRECTSOUND directSound;
if (directSoundCreate && SUCCEEDED(directSoundCreate(0, &directSound, 0)))
So in C you just pass a pointer to a LPDIRECTSOUND. I guess I need to make a LPDIRECTSOUND class extending the JNA Structure class in Java? Am I close to the answer here or way off?
JNA does support COM and there are several mappings already present in the com.sun.jna.platform.win32.COM package, including the IUnknown interface and the corresponding Unknown class implementing it.
You could implement an IDirectSound interface (optional) or just directly implement the class by extending Unknown. You will have to map the functions you need using _invokeNativeObject() (or the -Int and -Void variants).
I contributed several COM classes needed to query WMI in the WbemCli.java class that can serve as examples of how to pass those parameters. (Note: I probably shouldn't have used the I interface prefix on the concrete classes, but it's too late now.)
Function parameters are the vtableId, an array of objects for the arguments, and a class for the return type. To get the vtableId, you'll have to count the methods (0-indexed) in the directSoundVtbl struct in the header file. I don't have a copy of the authoritative Dsound.h file, but here's one possibility for that ordering (e.g., CreateSoundBuffer would have id 3). Inheriting from Unknown already gets you the first 3 functions in the Vtbl (id's 0, 1, and 2).
Here's a (completely untested) example to get you started.
public interface DSound {
#FieldOrder ({ "dwSize", "dwFlags", ... })
class DSBUFFERDESC extends Structure {
public int dwSize;
public int dwFlags;
// continue conventional JNA Structure mapping here
// may have to map nested structures
}
class DirectSoundBuffer extends Unknown {
// methods invoking COM similar to below
}
class DirectSound extends Unknown {
public DirectSound() {
}
public DirectSound(Pointer p) {
super(p);
}
public HRESULT CreateSoundBuffer(DSBUFFERDESC lpcDSBufferDesc, DirectSoundBuffer lplpDirectSoundBuffer, Unknown pUnkOuter) {
// CreateSoundBuffer is 4th method of directSoundVtbl in Dsound.h
return (HRESULT) _invokeNativeObject(3,
new Object[] { getPointer(), lpcDSBufferDesc, lplpDirectSoundBuffer, pUnkOuter }, HRESULT.class);
}
// Map whatever functions you need, or all of them!
}
}

Use a generic type to pass a specific class

I'm very new to programming language. My question might not even make sense. My environment is using java and trying to implement both ios and android apps in the same automation testing framework.
So, the idea is that any test script should be able to run on both the apps. Ex: one signin test script should be run for both ios and android.
I've decided to use interface and class implementation approach. The problem I'm facing is with test data. My company doesn't want to use excel. They want to use json for test data.
Here's my problem, look at the following line of code:
ValidBuy goodBuy = JsonFileReader.loadDaTa(TestBase.DATA_PATH, "good-buy.json", ValidBuy.class);
As you can see I have a class "ValidBuy" that has all the getters for a particular json file. I have another class "JsonFileReader" which takes the json filePath, fileName, and a class as an input and returns the data for that class name that I passed in. For this example I've passed ValidBuy.class
So, when I run a positive test, I'm passing "goodBuy" variable which is of type "ValidBuy". The problem starts here.
The test case is now specified with the data from goodBuy because it's type is "ValidBuy" and I'm passing goodBuy as a parameter.
Look at one of my extracted methods:
private void enterBuyInfo(ValidBuy goodBuy) {
itemPage = nativeApp.getItemPage(goodBuy);
itemPage.setItemName(goodBuy.getItemName());
itemPage.setItemSize(goodBuy.getItemSize());
itemPage.setItemDigitSSN(goodBuy.getSsn());
itemPage.clickContinue();
}
You can see those getters I'm using are coming from ValidBuy class.
If I run this test with the data for a badBuy:
InvalidBuy badBuy = JsonFileReader.loadDaTa(TestBase.DATA_PATH, "bad-buy.json", InvalidBuy.class);
It fails because now I have to change "ValidBuy" class with "InvalidBuy" class. Since, changing the parameter in the extracted method in every run is not possible, how can I make it more generic?
I want something like this:
TestData data = JsonFileReader.loadDaTa(RESOURCES_PATH, "good-client.json", InvalidBuy.class);
Here, TestData is generic. It could either be a class or interface (I don't know if that's possible) and the return type will be specified by whichever class I pass into the loadData() method. In this case InvalidBuy.class
The extracted method should look like this:
private void enterBuyInfo(TestData data) {
itemPage = nativeApp.getItemPage(data);
itemPage.setItemName(data.getItemName());
itemPage.setItemSize(data.getItemSize());
itemPage.setItemDigitSSN(data.getSsn());
itemPage.clickContinue();
}
If I can do this, I can use those extracted methods to create more tests.
I know I wrote a lot. I've only tried to make it as clear as possible. If it doesn't make any sense, just disregard it.
Any suggestions, ideas, code samples will be highly appreciated.
Firstly let me see if I understand your question. I think you are saying that loadData may return a value of type ValidBuy or InvalidBuy and you want to pass into it the class that you want returned. You then want to know how to use an interface that might represent either of these classes in your test methods so you can test various return values (both valid and invalid). You use the term "generic" in your question but I'm guessing you don't mean to use it in the specific way it's used in Java.
If I've understood your question correctly, then here's an answer:
Passing the class you wish to have returned into a method is an unusual usage and almost certainly not ideal. Better OOD would be to extract the common methods for all objects returned from loadData into an interface.
So:
interface Buy {
String getItemName();
boolean isValid();
}
class ValidBuy implements Buy {
#Override
public boolean isValid() {
return true;
}
...
}
class InvalidBuy implements Buy {
#Override
public boolean isValid() {
return false;
}
...
}
class JsonFileReader {
Buy loadData(Path path) {
...
}
}
Then your tests can look like:
#Test
void testValidBuy() {
assertTrue(reader.loadData(validPath).isvalid());
}
#Test
void testInvalidBuy() {
assertFalse(reader.loadData(invalidPath).isValid());
}
I realise I've simplified it a bit but hopefully you get the idea.

Using scala.collection.immutable.Map inside my java class

I get bellow exception from my java codes.
java.lang.ClassCastException: scala.collection.immutable.Map$Map1 cannot be cast to java.util.HashMap
at au.com.vroc.udf.medianUDF.update(medianUDF.java:79)
I am getting error in my spark application when I cast the buffer to HashMap of java.utill. This is my codes:
public void update(MutableAggregationBuffer buffer, Row input) {
if (!input.isNullAt(0)) {
HashMap currentBuffer=(HashMap) buffer.get(0);//getting exception here
//HashMap currentBuffer=new HashMap();
currentBuffer.put(input.getLong(0), input.getDouble(0));
//currentBuffer.add(currentMap);
buffer.update(0, currentBuffer);
}
}
I guess instead of java hashmap I have to use "scala.collection.immutable.Map$Map1" inside my java class. Can I use any tool in "JavaConversions" namespace.
Anyhep would be appreciated!
Simplest approach would likely be to use Scala Converters.
It should look something like this (not tested, but type-checks):
import scala.collections.JavaConverters
java.util.Map currentBuffer = JavaConverters.mapAsJavaMapConverter(buffer.get(0)).asJava();
Please note that it returns type-parameterized map (i.e. java.util.Map<K, V>), not the non-parameterized java.util.HashMapin your example - you might want to alter the rest of your code to work on the parameterized maps for better type safety.
You get java.util.Map you should use getJavaMap method:
java.util.Map<T, U> currentBuffer = (java.util.Map<T, U>) first.getJavaMap(0)
Note that this is not HashMap - initialized value is Encoded on update and decoded on get. To modify it, you have to make a copy.

Understanding [[I.class referenced in some Java source

I'm looking at some Java reflection sourcecode that goes like this:
Method fixTransparentPixels = TextureAtlasSprite.class.getDeclaredMethod("fixTransparentPixels", new Class[] { [[I.class });
The method being referenced is declared like so:
private void fixTransparentPixels(int[][] p_147961_1_) {...}
What I do not understand is the [[I.class part. Now, I get that the actual Class[] array is to determine which form of the declared method you want (what parameter types etc.), but what does [[I.class actually mean?
Furthermore, when I try to write this reflection code myself, my IDE gives me syntax errors on the [[I.class bit. Can anyone give me any info on this?
Cheers.
When using getDeclaredMethod(String name, Class<?>... parameterTypes) the parameterTypes must be the class of the parameter (obviously). So in this case fixTransparentPixels require a int[][], so the parameterTypes will be int[][].class.
This will works :
TextureAtlasSprite.class.getDeclaredMethod("fixTransparentPixels", int[][].class);
[[I is the internal name of the class for int[][]:
System.out.println(int[][].class.getName()); outputs [[I
or Class.forName("[[I") == int[][].class.
However, it's illegal to write [[I.class in source code. You should write int[][].class instead.

Java Using Strings as Code

Okay, so, here's what I have in code:
public void makeObject(int i){
String s = getString(i); //This returns the name of a class
new s(); //This is what I want to do
}
Can I do this?
No you can't do this, but what you're probably looking for is called 'reflection'.
Look at these series of (free) slides: http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply especially slide 11, but read the ones before that as well. It will give you an idea of what reflection is and a way to make a class by knowing the name (as a string) and how to instantiate a new instance of that class.
You can also find methods and fields by name, you can even modify existing classes in code.
Edit: for example the following code will return a class by string name
Class cls = Class.ForName("MyPackage.MyClassName");
return cls.NewInstance();

Categories