ClassCastException with Reflections - java

I try to analyze runtime information with reflections. The class I try to analyze has a static array of type me.instrumentor.InstrumentStackElem and I want to access and copy it using reflections.
The code looks like this:
final Field stack = this.object.getClass().getDeclaredField("ise_array");
stack.setAccessible(true);
final Object arr = stack.get(null);
final InstrumentStackElem[] tmp = new InstrumentStackElem[Array.getLength(arr)];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = (InstrumentStackElem) Array.get(arr, i);
}
When I try to run it, I get java.lang.ClassCastException: me.instrumentor.InstrumentStackElem cannot be cast to me.instrumentor.InstrumentStackElem at the line in the for loop.
Can anyone help me?

If it's sufficient for you to work on raw objects, you can try this solution. It enables you to work with arbitrary types and further you don't have to worry about different class loaders. A properly implemented toString() would be helpful too, I guess.
import java.lang.reflect.Array;
import java.lang.reflect.Field;
public class Main {
#SuppressWarnings("unused")
private static Integer[] targetArray = new Integer[] { 0, 1, 2, 3, 4, 5 };
public static void main(String[] args) throws Exception {
Field arrayMember = Main.class.getDeclaredField("targetArray");
arrayMember.setAccessible(true);
Object array = arrayMember.get(null);
int length = Array.getLength(array);
// get class of array element
Class<? extends Object> elementType = array.getClass().getComponentType();
Object copy = Array.newInstance(elementType, length);
for (int i = 0; i < length; i++) {
Array.set(copy, i, Array.get(array, i));
}
// if you know the type, you can cast
if (Integer[].class.isInstance(copy)) {
System.out.println("Integer[].class.isInstance(copy) == true");
Integer[] copiedArray = Integer[].class.cast(copy);
for (Integer i : copiedArray)
System.out.println(i);
} else {
for (int i = 0; i < length; i++) {
System.out.println(Array.get(copy, i));
}
}
}
}
OUTPUT
Integer[].class.isInstance(copy) == true
0
1
2
3
4
5

Related

Queue does not take parameters in java

I have a problem in my code
I'm not being able to add Queue
When I tried to add this code
Queue<Integer> myqu = new LinkedList<>();
for (int i = 0; i <= mySecondArray.length + 1; i++){
myqu.add(mySecondArray[i]);
}
To this code
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
class test{
static class Queue{
static Stack<Integer> s1 = new Stack<Integer>();
Queue<Integer> myqu = new LinkedList<>();
static int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
static int[] mySecondArray = new int[10];
static void enQueue(){
for (int i = 0; i < intArray.length; i++){
s1.push(intArray[i]);
}
System.out.printf("\nBefore multiply operation\n");
System.out.printf("%s \n",s1);
System.out.printf("\nAfter multiply operation\n");
Integer edit = s1.pop();
System.out.printf("[");
for (int i = 1; i <= s1.size() + 1; i++){
mySecondArray[i] = i * 2;
edit = Integer.valueOf(i) * 2;
System.out.printf("%s",edit);
System.out.printf(", ");
}
System.out.printf("]");
for (int i = 0; i <= mySecondArray.length + 1; i++){
myqu.add(mySecondArray[i]);
}
}
};
public static void main(String[] args)
{
Queue q = new Queue();
q.enQueue();
}
}
It says " error: type Queue does not take parameters
Queue myqu = new LinkedList();"
Could you correct the code, Please
You are geeting this issue because your class name and interface Queue name is same.
Change you class name and this issue will resolve like:
static class SampleQueue{
..your code
}
And change your main method for new name:
public static void main(String[] args)
{
SampleQueue q = new SampleQueue();
q.enQueue();
}
If you're trying to use java.util.Queue, why are you creating your own inner static class called Queue? Rename your Queue class, and it's also declared static, so you can't instantiate it with new
Also you myqu is not declared static, so you need to fix that as well, I renamed it myQueue in the code below as per naming conventions
public class test {
static class QueueUtil {
static Stack<Integer> s1 = new Stack<Integer>();
static Queue<Integer> myQueue = new LinkedList<>();
static int[] intArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
static int[] mySecondArray = new int[10];
static void enQueue() {
for (int value : intArray) {
s1.push(value);
}
System.out.print("\nBefore multiply operation\n");
System.out.printf("%s \n", s1);
System.out.print("\nAfter multiply operation\n");
Integer edit = s1.pop();
System.out.print("[");
for (int i = 1; i <= s1.size() + 1; i++) {
mySecondArray[i] = i * 2;
edit = i * 2;
System.out.printf("%s", edit);
System.out.print(", ");
}
System.out.print("]");
for (int i = 0; i <= mySecondArray.length + 1; i++) {
myQueue.add(mySecondArray[i]);
}
}
}
public static void main(String[] args) {
QueueUtil.enQueue();
}
}
This code should fix your issue that you asked about, but I think you're not going to get the results you're expecting...
I recommend reading up on how, when and why to use static, there are a lot of great posts on here.

How to create a constructor that takes an array parameter and initialise the values in an underlying array?

How to create a constructor that takes an array parameter and initialize the values in an underlying array in Java?
The constructor should do so such that when I call it in main, passing it an array as a parameter, the initialized object that is output by the constructor is the same as the array parameter.
public class MyClass<E> {
protected E[] underlyingArray;
public MyClass(Object[] arr) {
underlyingArray = (E[]) new Object[arr.length];
for (int i = 0; i < arr.length; i++) {
this.underlyingArray[i] = (E) arr[i];
}
}
public void print() {
for (int i = 0; i < size; i++) {
System.out.println(i + ": " + underlyingArray[i]);
}
}
public static void main(String[] args) {
final String[] array = { "d", "e", "f" };
final MyClass myArray = new MyClass((Object[])array);
myArray.print();
Expected:
0: d
1: e
2: f
Actual:
I get an index out of bounds exception as myArray was never initialized after passing arr through myClass constructor.
I have tried several combinations in MyClass constructor but have not been able to initialize the underlying array myArray successfully.
The code works, but there is no need of generics in your case
class MyClass {
private Object[] underlyingArray;
MyClass(Object[] arr) {
underlyingArray = new Object[arr.length];
for (int index = 0; index < arr.length; index++) {
this.underlyingArray[index] = arr[index];
}
}
public void print() {
for (int index = 0; index < underlyingArray.length; index++) {
System.out.println(index + " : " + underlyingArray[index]);
}
}
public static void main(String[] args) {
final String[] array = { "d", "e", "f" };
final MyClass myArray = new MyClass(array);
myArray.print();
}}
The code works just fine. Check your print()method. This works for me.
public class MyClass<E> {
protected E[] underlyingArray;
public MyClass(Object[] arr) {
underlyingArray = (E[]) new Object[arr.length];
for (int i = 0; i < arr.length; i++) {
this.underlyingArray[i] = (E) arr[i];
}
}
public void print(){
for(int i=0;i<underlyingArray.length;i++){
System.out.println(i+": "+underlyingArray[i]);
}
}
}
public static void main(String[] args) {
final String[] array = { "d", "e", "f" };
final MyClass myArray = new MyClass((Object[])array);
myArray.print();
}
Thanks everyone, the reason why my code did not work was because of an additional size variable that I did not set (not included in snippet) as part of initialization of the constructor. That explains the indexOutOfBounds exception I got as the size was always 0.
Apologies for raising a question with incomplete information. The code does work fine in the snippet above. Deserved the downvote. Thanks again.

How do I initialize elements of an array, 1 through 10, and then use that constructor in a method that will print the elements?

I have an assignment for object-oriented programming class. I've been trying to take the values of an array that were initialized in a constructor, and use the values from that constructor to print them in a different method called printArrayValues. I cannot seem to 'call' or return the values in the method.. I've been troubleshooting for hours and I'm getting frustrated.
The assignment's steps are as follows:
The constructor for the ExerciseOne class initializes and instantiates myArray as an array of ten integers, and initializes the elements of the array with the values 1 through 10, using a for-loop.
You must assign the values in terms of the for-loop index variable, for example, i.
The class has a method called printArrayValues that uses a for-loop and System.out.print() statement to print out the values of the elements of the array, as shown in the sample output.
This method has no parameters, and no return value.
I've tried creating a new variable in the constructor, and then calling it in the method, but it's not working.
public class ExerciseOne {
public int[] myArray;
public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();
}
ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray = new int[i];
}
}
public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a] + 1));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}
}
}
//
//public void displayArrayProduct() {
// for (int : myArray) {
//
// }
//
//}
}
I got frustrated and just created the loop, to initialize it, in the method. This is incorrect for the assignment, but I wanted to move on. Honestly I'm very lost at this point and I'm sorry if that makes it more difficult to help me.
You can try this code.
public class ExerciseOne {
public int[] myArray = new int[10];
public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();
}
ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray[i] = i+1;
}
}
public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a]));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}
}
}
}
Output: myArray = {1,2,3,4,5,6,7,8,9,10};
You are initializing the same array twice. Your program will work the same if you use any of below :
myArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9 , 10};
or
myArray = new int[10]; for (int i = 0; i < myArray.length; i++) { this.myArray[i]=i+1; }
as your array is not 2d array so you cant assign another array on elements of array.
this.myArray = new int[i]; // not correct
I've written and tested the below and it returns the output you need. Please note that it's been written in C# for a console application. If it helps then please remember to vote for me.
Create your ExerciseOne class like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
public class ExerciseOne
{
int[] eo;
public ExerciseOne()
{
eo = new int[10];
for (int i = 0; i <= 9; i++)
{
eo[i] = i + 1;
}
printArrayValues();
}
public void printArrayValues()
{
foreach (var item in eo)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
Then call the class like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
ExerciseOne one = new ExerciseOne();
}
}
}

JUnit: test builder with private field

I'm a beginner and I have a problem with JUnit test in the constructor of a class.
The class that I want to test is called IntSortedArray and is as follows:
public class IntSortedArray {
private int[] elements;
private int size;
public IntSortedArray() {
this.elements = new int[16];
this.size = 0;
}
public IntSortedArray(int initialCapacity) throws IllegalArgumentException {
if(initialCapacity < 0) {
throw new IllegalArgumentException("Error - You can't create an array of negative length.");
}
else {
elements = new int[initialCapacity];
size = 0;
}
}
public IntSortedArray(int[] a) {
elements = new int[a.length + 16];
for(int i = 0; i < a.length; i++)
elements[i] = a[i];
size = a.length;
insertionSort(elements);
}
//other code...
}
With Eclipse I created a class for JUnit:
public class IntSortedArrayUnitTest {
private IntSortedArray isa;
#Test
public void testConstructorArray16Elements() {
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.elements) **<-- ERROR**
expected += 1;
assertEquals(expected, 16);
}
}
I started to write a test class with the intention to test all the methods of the class IntSortedArray, including constructors.
The first method testConstructorArray16Elements() wants to test the first builder.
So I thought I would check if the creation of the array elements is done properly, so the for loop counts how long elements and make sure it along 16 (as required).
But Eclipse generates (rightly) a mistake because elements is private.
How can I fix this error? I don't want to put the public field and if possible I would like to avoid creating a method public int[] getElements().
What do you recommend?
Another question: I can do two assert the same method? One to test the length of the array and the other to test that size is 0.
I hope not to have made big mistakes, this is the first time I use JUnit.
PS: how can I test the second constructor?
Thank you very much!
It looks like your class fields are declare as private but you trying to access then from outside the class. You need to provide the accessors methods in you class to make them visible:
private int[] elements;
private int size;
public static final int MAX = 16;
public int[] getElements() { ... }
public int getSize() { return size; }
Then you will be able to write below code:
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.getElements()) {
expected += 1;
}
assertEquals(expected, IntSortedArray.MAX );
It looks like your constructor has created an array for 16 integers, but does not initialize it with any value. To do that you should have below code:
public IntSortedArray() {
this.elements = new int[MAX];
this.size = 0;
for (int i=0 ; i < MAX ;i++) {
elements[i] = i;
size++;
}
}
You'll have to write a getter method for your array, or implement an Iterator

Array of a class (Java)

I cannot seem to find the correct way to write an array of a class. In this form no errors are thrown on compiling, but I receive an error when I try to make use of the array / class. The array of classes is in a class named HashTable (I'm required to write my own for an assignment) and I am testing it with the code below:
theHashTable.insert("aa", "ab");
Here is the HashTable class:
Edit: As pointed out by Aniket, fileNames was not being initialized. I corrected this below but receive the same error.
private class HashTable {
private class Value {
ArrayList<String> fileNames;
String word;
Value() {
fileNames = new ArrayList<String>();
}
}
private int currentSize = 101;
private Value[] items;
private HashTable() {
items = new Value[currentSize];
for (int i = 0; i < currentSize; i++) items[i] = new Value();
}
private int hash(String in) {
int out = 0;
for (int i = 0; i < in.length(); i++) out += 37*out+in.charAt(i);
out %= currentSize;
if (out < 0) out += currentSize;
return out;
}
public void insert(String inW, String inF) {
int index = hash(inW);
index = 0;
if (items[index].word.length() == 0) {
items[index].word = inW;
items[index].fileNames.add(inF);
}
else if (items[index].word.compareTo(inW) == 0) items[index].fileNames.add(inF);
else System.out.println("Collision");
}
}
fileNames ArrayList in your Values class is never initialized. Write a constructor for Values and Initialize fileNames.
Declare fileNames in your inner class value with initialization(line 3 in your sample code) as:
ArrayList<String> fileNames = new ArrayList<String>();

Categories

Resources