Creating array of generic object
hello, what i want to do is something like:
public class AClass<K extends SomeObject>{
SomeObject[] AnArray;
public void amethod() {
AnArray=new K[10];
}So I want to create an array of some kind of object at runtime without already know the kind of the object. The thing is that I think that generics are only "known" at compiling time, so this AnArray=new K[10]; is propably completely wrong but I cannot think of any other way of creating an array without knowing in advance the kind of object....So if someone could enlighten me on how to do this...
if this is of any help the reason i want to have such implementation is that this array is supposed to be a hashmap and the SomeObject is supposed to be a super class of some different kind of LinkedList classes, so I want the hashmap to be flexible on what kind of list will be used. Suggestions for completely different approach are also welcome offcourse, but I would prefer it if someone could give some brief explaination on how manipulating such a generic array issue...
Hi Fraksia,
Unfortunately, array creation of type parameters is not allowed, so you can't
say new T[3]; That is because T doesn't exist at compile time. It is erased.
It is misleading - I know. Because when you say
AClass<SomeObject> aclass=new AClass<SomeObject>();you might thing that T becomes SomeObject in your class wheres
what that does is that whenever you expect your type parameter in
the calling code, compiler will insert a cast. See the example below:
class MyClass<T> {
T o;
public MyClass(T o) {
this.o=o;
public T get() {
return o;
class CallingClass {
public static void main(String[] args) {
MyClass<String> m=new MyClass<String>("Test");
String o=m.get(); //no cast needed here
}Benefit: increased type safety, no casts needed in the CallingClass.
What really happens is:
class MyClass {
Object o;
public MyClass(Object o) {
this.o=o;
public Object get() {
return o;
class CallingClass {
public static void main(String[] args) {
MyClass m=new MyClass("Test);
String s=(String)m.get(); // compiler inserts cast here based on your type parameter
}That is why you can't do what you wanted - because "there is no spoon" ;)
Generics in Java are only a compile time feature.
Cheers,
Adrian
Similar Messages
-
Create Attachments to Generic Object Services from Webdynpro appliccation
Hi,
I have requirement to Create Attachments to Generic Object Services(GOS) in equipment master (IE03) from webdynpro when a user clicks on upload button and also allow the user to delete the attachments .
Can anyone advice me of any Function Modules or logic to use from Web GUI.
I used below logic from R/3 to create attachments, but from webdynpro this method doesn't work.
DATA lo_attachment TYPE REF TO cl_gos_document_service.
CREATE OBJECT lo_attachment.
CALL METHOD lo_attachment->create_attachment
EXPORTING is_object = ls_object
IMPORTING ep_attachment = lp_attachment
Your inputs are appreciated.
Thanks
Rajesh YaldaHi,
try using the Class CL_GOS_SRV_ATTACHMENT_CREATE with Method EXECUTE_ITS.
best regards,
Michael -
Create Attachment through Generic Object Services (BC-SRV-GBT)
Hello experts,
I have one question about a storing of document in this functionality. As you know there are several ways of storing a document to some object.
1. Using the menu: "Create - Create Attachment"
2. Using the menu: "Create - Store Business Document"
In the first case the document will be saved in SAP Database (Please correct me if I mistake). In the second case an optical archive must be connected to the SAP System. Can I use an optical archive in the first case?
PS. When I use the second way I don't see the name of document in the Attachment List. If use "Create - Create Attachment" - it is OK.
Thanks advance for any help.
Your faithfully,
Alekseev Aleksandr
Edited by: Aleksandr Alekseev on May 5, 2008 6:05 AMHi Friend,
You have posted your query in wrong forum.
Pls post your query in BPM and Workflow Forum. -
Generic Object Services - Create Attachment
Hi SDN experts
In the trip details page of the travel expense manager, may i know what Function Module does the "Create Attachment" functionality in the Generic Object Services trigger? Appreciate if anyone is able to provide me with an answer. Thank you
Regards
LVYou are in great trouble. Repeated posting of a single thread will really make you a Guest.
You have replicated this post in SEVEN forums.
Generic Object Services - Create Attachment in
Generic Object Services - Create Attachment in
Generic Object Services - Create Attachment in
Generic Object Services - Create Attachment in
Generic Object Services - Create Attachment in
Generic Object Services - Create Attachment in
Generic Object Services - Create Attachment in
As you are new to the forum please Read the [Forum Rules|http://wiki.sdn.sap.com/wiki/x/FgQ] before posting more.
Regards
Karthik D -
In the workflow we usually create generic objects and assign values and refer them through out the process. But instead of creating generic objects on the fly in the workflows we want to reuse the generic objects created as a template. We see that the BPE gives a provision to create such templates/generic objects.
But how do we refer these generic objects in workflow.you have to override the NavigationHandler class
-
How to create a Generic Object Services for a standard tcode.
Hi,
We have a requirement where we are depreciating the assets (standard transaction ABAA) using a custom BDC program. We need to maintain a history (called audit trail) for the particular asset that has been depreciated using this program. For this audit train we have been asked to use "Generic Object Services" in transaction code ABAA.
Unfortunately, Generic object services are not available in this transaction code. Can you please suggest me how to create "Generic Object Services" for a particular standard transaction code. Also, we have show the details of custom workflow that follows the approval process in order to depreciate the asset. how to show this workflow details using Generic Services. This is a very critical issue, any help will be very help ful.
Please let me know should you require more information on this topic.
Thanks,
AshishInstead of copyg the std fm to z, do the following,
1. Go to se37 open FM VIEW_KURGV in display mode.
2. Click on the spiral icon on the top.
3. Then in menu go edit->enhancment options -> show implicit enhancement
4. """""""""""""""""""""" kind of lines will appear in the cde, just rt click on the line at the place u want to insert the code and select
enhancement implementation create.
5. Give apropriate name for thi , it will inset a n place to write your code.
This is an std sap methodology and is supported in upgradde also. -
Generic Object Services ; create attachment function grey out in Tcode KA03
Hi all,
I would like to know how can I enable create attachment function in GOS toolbar in Tcode KA03.
Currently it was grey out.
However, was tried to use the same function in KS03 and it works.Please help. Thanks!I just found the solution...
SAP note : 961572
Symptom</u>
In the transactions for displaying cost elements (KA03) and changing cost elements (KA02), the 'Services for Object' function does not work correctly, as most Generic Object Services are unavailable.
Other terms
KA03, KA02, SWO1, K_OBJECT_SERVICES_INITIALIZE, BUS1059, BUS1030
Reason and Prerequisites
The problem is caused by a program error.
Solution
Implement the attached program corrections
Then go to Transaction SW01 (Business Object Builder), enter BUS1059 as the object type, click Change, and make the following changes:
Navigate to Methods -> RevenueType.Display, press F2 to select it, and go to the 'ABAP' tab page: Select the 'Transaction' radio button, enter the name as KA03, and click 'Save'
Navigate to Attributes -> Attribute properties, select the 'Mandatory' checkbox, and click 'Save'
Then change the release status by navigating as follows:
Edit -> Change Release Status -> Object Type -> To implemented
Edit -> Change Release Status -> Object Type -> To released
Then double-click BUS1059 (or select using F2) in SWO1 to reach the 'General' tab page, which should appear as follows:
ObjectType BUS1059 Revenue element
Object Name RevenueType
Program RBUS1059
Objtype status generated Saved released -
How to create an array of generics?
I have the following snippet of code using array of vectors:
Vector[] tmpArr = new Vector[n];
for(int j=0; j<n; j++)
tmpArr[j] = new Vector();
String str = ...
if (!tmpArr[j].contains(str))
tmpArr[j].add(str);
And I want to convert to generics:
Vector<String>[] tmpArr = new Vector<String>[n];
for(int j=0; j<n; j++)
tmpArr[j] = new Vector<String>();
String str = ....
if (!tmpArr[j].contains(str))
tmpArr[j].add(str);
But the first row gives me an error:
-->Generic array creation.
If I change it in
Vector<String>[] tmpArr = new Vector<String>[n];
(as I've seen in a pdf by G.Bracha talking aout collections)
it gives me the error:
-->cannot find symbol
-->method add(String)
in the
tmpArr[j].add(str);
row.
The only way it seems to work is
Vector<String>[] tmpArr = new Vector[n];
but it gives me the unchecked conversion warning.
How can I create an array of generics?
Thank you!
MatteoYou can't
Actually, that depends on the exact definition of a generic array. If by generic array someone means "an array comprised of elements defined by a type parameter", there is a solution.
import java.lang.reflect.Array;
public class Something<T> {
private final Class<T> type;
public Something(Class<T> type) {
this.type = type;
public String getTypeName() {
return this.type.getName();
public T[] newArray(final int length) {
return (T[]) Array.newInstance(this.type, length);
}The constructor introduces the type information (T) to the runtime environment, which means an instance of Something will know its type. Method newArray therefore does not cause a warning on unchecked type conversion, so this approach is typesafe.
// Type parameter class is demanded by constructor...
Something<String> stringThing = new Something<String>(String.class);
// Cheating won't work, because the compiler catches the error...
Something<Vector> vectorThing = new Something<Vector>(Integer.class);This approach, however, doesn't enable you to create an array of typed elements (like Vector<String>[]). If that is the definition of a generic array, then it is indeed not possible to create one.
After all, while Vector[].class exists and can be resolved at runtime, there's no such thing as Vector<String>[].class, so there's no way you could provide the class definition of the component type to the constructor of Something.
This may be a surprise to mdt_java, because if I remember correctly, templates in C++ cause actually different classes to be created for 'generic' types. This is not the case with Java. -
How to create an array of an object,
Hi,
Trying this in Oracle 10.3 studio, I have to use a web service, I have re-catalogued the web service succesfully,
I am getting compilation error whenI try to create an array of a object,
Services.PackageTrackingService.PackageTrackingItem[] pkgTrackingItem = new Services.PackageTrackingService.PackageTrackingItem[2];
I am giving the array size as 2,
The comilation error is showing as
Multiple markers at this line
- statement is expected
- Expecting ';' but 'pkgTrackingItem' was found
- expression is expected
Is there any other way to create the array?
Thanks in advance.
-SreeHi,
Please declare the array in following manner.
Services.PackageTrackingService.PackageTrackingItem[] pkgTrackingItem;
Now you can insert the element into the array by pkgTrackingItem[0], pkgTrackingItem[1] etc.
Bibhu -
Is there any deference between generic object and create view
In creating account for user in idm,I initialized a generic object
we can do it with create view also
in this process,is there any differences in using create view/generic object
I don't know exactly which one we have to useHi,
Set the log level to 2 and the queries generated by the obiee and sql will be same.
Thanks,
Sandy -
Create Class objects from an Array of File Objects
Hi There,
I'm having extreme difficulty in trying to convert an array of file objects to Class objects. My problem is as follows: I'm using Jfilechooser to select a directory and get an array of files of which are all .class files. I want to create Class objects from these .class files. Therefore, i can extract all the constructor, method and field information. I eventually want this class information to display in a JTree. Very similar to the explorer used in Netbeans. I've already created some code below, but it seems to be throwing a NoSuchMethodError exception. Can anyone please help??
Thanks in advance,
Vikash
/* the following is the class im using */
class FileClassLoader extends ClassLoader {
private File file;
public FileClassLoader (File ff) {
this.file = ff;
protected synchronized Class loadClass() throws ClassNotFoundException {
Class c = null;
try {
// Get size of class file
int size = (int)file.length();
// Reserve space to read
byte buff[] = new byte[size];
// Get stream to read from
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream (fis);
// Read in data
dis.readFully (buff);
// close stream
dis.close();
// get class name and remove ".class"
String classname = null;
String filename = file.getName();
int i = filename.lastIndexOf('.');
if(i>0 && i<filename.length()-1) {
classname = filename.substring(0,i);
// create class object from bytes
c = defineClass (classname, buff, 0, buff.length);
resolveClass (c);
} catch (java.io.IOException e) {
e.printStackTrace();
return c;
} // end of method loadClass
} // end of class FileClassLoader
/* The above class is used in the following button action in my gui */
/* At the moment im trying to output the data to standard output */
private void SelectPackage_but2ActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rVal = f.showOpenDialog(Remedy.this);
// selects directory
File dir = f.getSelectedFile();
// gets a list of files within the directory
File[] allfiles = dir.listFiles();
// for loop to filter out all the .class files
for (int k=0; k < allfiles.length; k++) {
if (allfiles[k].getName().endsWith(".class")) {
try {
System.out.println("File name: " + allfiles[k].getName()); // used for debugging
FileClassLoader loader = new FileClassLoader(allfiles[k]);
Class cl = loader.loadClass();
//Class cl = null;
Class[] interfaces = cl.getInterfaces();
java.lang.reflect.Method[] methods = cl.getDeclaredMethods();
java.lang.reflect.Field[] fields = cl.getDeclaredFields();
System.out.println("Class Name: " + cl.getName());
//print out methods
for (int m=0; m < methods.length; m++) {
System.out.println("Method: " + methods[m].getName());
// print out fields
for (int fld=0; fld < fields.length; fld++) {
System.out.println("Field: " + fields[fld].getName());
} catch (Exception e) {
e.printStackTrace();
} // end of if loop
} // end of for loop
packageName2.setText(dir.getPath());
}It's throwing the exeption on the line:
FileClassLoader loader = new FileClassLoader(allfiles[k]);
I'm sure its something to do with the extended class i've created. but i cant seem to figure it out..
Thanks if you can figure it out -
I want to create a 3*3 multidimensional array of label objects
i want to initialize the array with label objects help me
If this post answers your question or helps, please mark it as such.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="init();">
<mx:Script>
<![CDATA[
import mx.controls.Label;
private var arr:Array = new Array();
private function init():void{
for(var a:uint=0;a<10;a++){
var inArr1:Array = new Array();
for(var b:uint=0;b<10;b++){
var inArr2:Array = new Array();
for(var c:uint=0;c<10;c++){
var lbl:Label = new Label();
lbl.text = "Label" + a + b + c;
inArr2.push(lbl);
inArr1.push(inArr2);
arr.push(inArr1);
for each(var xArr:Array in arr){
for each(var yArr:Array in xArr){
for each(var lbl2:Label in yArr){
txt.text += lbl2.text + " ";
]]>
</mx:Script>
<mx:TextArea width="100%" height="100%" id="txt"/>
</mx:Application> -
I am unable to create my two dimensional objects
suppose if
class MyObject
int i;
MyObject [][]o;
how to create this kind of objects
pls help me for thiswhy don't you try answering the question? I'm pretty sure the OP just posted a generic example that is not supposed to compile okay, '.....' is also an invalid keyword.
OP:
google is your friend. Just search for "java 2d array" and you'll get plenty of answers. -
Has any of the OOP programmers out there ever developed a generic object manager? What I mean by this is a an Object in LabVIEW that can hold references to all objects in an application that can be accessed generically through a name input and not via know each individual class type. I have been trying to create a class that essentially has as its attributes an array of LV Objects since all objects descend from this class. I am struggling with getting the specific class back from the generic class. If I probe the array it shows the class specific type.
So what I am trying to do is search an array of standard LabVIEW Objects for a specific LabVIEW type. Here I created an array of LabVIEW object by casting specific classes to the most generic class - LabVIEW Object. Then I want to search an array for a specific class by taking a specific class constant and casting it to a more generic class. It seems like it keeps the reference information (ID).
Any thoughts?LV2009 added a function which is probably crucial to delivering a nice solution to this problem. The function is called Preserve Run-time Class. It allows you to propogate the strict type of an object through a subVI that is coded to operate on a more generic class type.
Here's an example written in LV2009 for a simple class that stores any other LV class object by name.
Jarrod S.
National Instruments
Attachments:
Temp.zip 33 KB -
I can't seem to get individual elements when comparing 2 arrays using Compare-Object
My backup software keeps track of servers with issues using a 30 day rolling log, which it emails to me once a week in CSV format. What I want to do is create a master list of servers, then compare that master list against the new weekly lists to identify
servers that are not in the master list, and vice versa. That way I know what servers are new problem and which ones are pre-existing and which ones dropped off the master list. At the bottom is the entire code for the project. I know it's a bit much
but I want to provide all the information, hopefully making it easier for you to help me :)
Right now the part I am working on is in the Compare-NewAgainstMaster function, beginning on line 93. After putting one more (fake) server in the master file, the output I get looks like this
Total entries (arrMasterServers): 245
Total entries (arrNewServers): 244
Comparing new against master
There are 1 differences.
InputObject SideIndicator
@{Agent= Virtual Server in vCenterServer; Backupse... <=
What I am trying to get is just the name of the server, which should be $arrDifferent[0] or possibly $arrDifferent.Client. Once I have the name(s) of the servers that are different, then I can do stuff with that. So either I am not accessing the array
right, building the array right, or using Compare-Object correctly.
Thank you!
Sample opening lines from the report
" CommCells > myComCellServer (Reports) >"
" myComCellServer -"
" 30 day SLA"
CommCell Details
" Client"," Agent"," Instance"," Backupset"," Subclient"," Reason"," Last Job Id"," Last Job End"," Last Job Status"
" myServerA"," vCenterServer"," VMware"," defaultBackupSet"," default"," No Job within SLA Period"," 496223"," Nov 17, 2014"," Killed"
" myServerB"," Oracle Database"," myDataBase"," default"," default"," No Job within SLA Period"," 0"," N/A"," N/A"
Entire script
# things to add
# what date was server entered in list
# how many days has server been on list
# add temp.status = pre-existing, new, removed from list
# copy sla_master before making changes. Copy to archive folder, automate rolling 90 days?
## 20150114 Created script ##
#declare global variables
$global:arrNewServers = @()
$global:arrMasterServers = @()
$global:countNewServers = 1
function Get-NewServers
Param($path)
Write-Host "Since we're skipping the 1st 6 lines, create test to check for opening lines of report from CommVault."
write-host "If not original report, break out of script"
Write-Host ""
#skip 5 to include headers, 6 for no headers
(Get-Content -path $path | Select-Object -Skip 6) | Set-Content $path
$sourceNewServers = get-content -path $path
$global:countNewServers = 1
foreach ($line in $sourceNewServers)
#declare array to hold object temporarily
$temp = @{}
$tempLine = $line.Split(",")
#get and assign values
$temp.Client = $tempLine[0].Substring(2, $tempLine[0].Length-3)
$temp.Agent = $tempLine[1].Substring(2, $tempLine[1].Length-3)
$temp.Backupset = $tempLine[3].Substring(2, $tempLine[3].Length-3)
$temp.Reason = $tempLine[5].Substring(2, $tempLine[5].Length-3)
#write temp object to array
$global:arrNewServers += New-Object -TypeName psobject -Property $temp
#increment counter
$global:countNewServers ++
Write-Host ""
$exportYN = Read-Host "Do you want to export new servers to new master list?"
$exportYN = $exportYN.ToUpper()
if ($exportYN -eq "Y")
$exportPath = Read-Host "Enter full path to export to"
Write-Host "Exporting to $($exportPath)"
foreach ($server in $arrNewServers)
$newtext = $Server.Client + ", " + $Server.Agent + ", " + $Server.Backupset + ", " + $Server.Reason
Add-Content -Path $exportPath -Value $newtext
function Get-MasterServers
Param($path)
$sourceMaster = get-content -path $path
$global:countMasterServers = 1
foreach ($line in $sourceMaster)
#declare array to hold object temporarily
$temp = @{}
$tempLine = $line.Split(",")
#get and assign values
$temp.Client = $tempLine[0]
$temp.Agent = $tempLine[1]
$temp.Backupset = $tempLine[2]
$temp.Reason = $tempLine[3]
#write temp object to array
$global:arrMasterServers += New-Object -TypeName psobject -Property $temp
#increment counter
$global:countMasterServers ++
function Compare-NewAgainstMaster
Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
Write-Host "Total entries (arrNewServers): $($countNewServers)"
Write-Host "Comparing new against master"
#Compare-Object $arrMasterServers $arrNewServers
$arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
Write-Host "There are $($arrDifferent.Count) differences."
foreach ($item in $arrDifferent)
$item
## BEGIN CODE ##
cls
$getMasterServersYN = Read-Host "Do you want to get master servers?"
$getMasterServersYN = $getMasterServersYN.ToUpper()
if ($getMasterServersYN -eq "Y")
$filePathMaster = Read-Host "Enter full path and file name to master server list"
$temp = Test-Path $filePathMaster
if ($temp -eq $false)
Read-Host "File not found ($($filePathMaster)), press any key to exit script"
exit
Get-MasterServers -path $filePathMaster
$getNewServersYN = Read-Host "Do you want to get new servers?"
$getNewServersYN = $getNewServersYN.ToUpper()
if ($getNewServersYN -eq "Y")
$filePathNewServers = Read-Host "Enter full path and file name to new server list"
$temp = Test-Path $filePathNewServers
if ($temp -eq $false)
Read-Host "File not found ($($filePath)), press any key to exit script"
exit
Get-NewServers -path $filePathNewServers
#$global:arrNewServers | format-table client, agent, backupset, reason -AutoSize
#Write-Host ""
#Write-Host "Total entries (arrNewServers): $($countNewServers)"
#Write-Host ""
#$global:arrMasterServers | format-table client, agent, backupset, reason -AutoSize
#Write-Host ""
#Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
#Write-Host ""
Compare-NewAgainstMasterdo not do this:
$arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
Try this:
$arrDifferent = Compare-Object $arrMasterServers $arrNewServers -PassThru
¯\_(ツ)_/¯
This is what made the difference. I guess you don't have to declare arrDifferent as an array, it is automatically created as an array when Compare-Object runs and fills it with the results of the compare operation. I'll look at that "pass thru" option
in a little more detail. Thank you very much!
Yes - this is the way PowerShell works. You do not need to write so much code once you understand what PS can and is doing.
¯\_(ツ)_/¯
Maybe you are looking for
-
Hi All, We have been trying to update Price in PO at the time of PGI using USEREXIT SAVE_DOCUMENT triggering BAPI_PO_CHANGE. It is failing because PO cannot be edited while PGI is under process/Outbound Delivery is being worked on. Can anyone please
-
my mac recently got stolen, after getting a new one i had to reinstall logic studio, but after moving house i have lost the serial number, does anyone know how to get a new one?
-
I can get the x values of each function to display on the front panel with no problems, but I have not been able to acquire this information from the front panel.
-
Switch to "Source Code-Based" mode in class builder
hi, while doing the tutorial http://help.sap.com/saphelp_nwpi71/helpdata/en/67/6b5bbb681e4f10b44bc2d6c4167b02/content.htm i came across the step, ... Switch to Source Code-Based mode , in the class builder, but in my workbench it is not available. i
-
While playing video system crashes
While playing video system crashes all the times. I am using WIN 7 and also had skype installed(don't know if that would cause it). Any idea how to fix that?