working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,062 snippets matching: reflection

    public by dave83  223910  8  7  0

    How to run methods in class marked with specific Java annotation

    The snippet shows how to invoke only methods of a class marked with specific annotation. The list of methods class (MyTest) is returned using reflection. Annotations are returned via getAnnotation() method. The method is executed via invoke() method.
    import java.lang.reflect.Method;
    
    public class MyTest {
    
        @MyAnnotation
        public void method1() {
          System.out.println("method1");
        }
    
        public void method2() {
          System.out.println("method2");
        }
        
        @MyAnnotation
        public void method3() {
          System.out.println("method3");
        }
        
        public static void main(String[] args) {
    
            MyTest runner = new MyTest();
            Method[] methods = runner.getClass().getMethods();
    
            for (Method method : methods) {
                MyAnnotation annos = method.getAnnotation(MyAnnotation.class);
                if (annos != null) {
                    try {
                        method.invoke(runner);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    } 
                            

    public by cghersi  2242  4  6  0

    How to create an instance of a generic class in Java

    This is the simplest way to create an instance of an object, given its class
    T d = null;
    try {
    	d = (T)clazz.newInstance();
    } catch (InstantiationException e) {
    	log.error("Cannot create instance of class " + clazz, e);
    	return;
    } catch (IllegalAccessException e) {
    	log.error("Cannot create instance of class " + clazz, e);
    	return;
    }

    public by cghersi  1785  0  4  1

    Load a class and call a static method with reflection in java

    This is the simplest method to realize an abstract factory, extendible via reflection. In this case you don't nee to know in advance the libraries that will be attached to your project, but just a convetion on the name of th class to load!
    public static final AbstractFactory loadFactory(){
    		if (concreteFactory == null){
    			try {
    				String name = "mypackage.classname";
    
    				Method getVendorInterface = Class.forName(name).getMethod("getFactory", null);
    				concreteFactory = (ProtocolAbstractFactory) getVendorInterface.invoke(null, null);
    			} catch (Exception e) {
    				log.error("Error loading abstract factory: " + e);
    				return null;
    			}
    		}
    	
    		return concreteFactory;
    	}

    public by sercani  3901  1  7  4

    Reading Excel file and inserting into List with Serialization

    This class reads a sheet from excel file and insert into a list by matching the column names at sheet with member names of the class.
    using System.Data;
    using System.Data.Odbc;
    using System.Reflection;
    using System.Runtime.Remoting;
    using System;
    using System.Collections.Generic;
    
    public class ExcelReader
    {
        public List<DataItem> DataList = new List<DataItem>();
        public List<AnotherDataItem> AnotherDataList = new List<AnotherDataItem>();
        string fileName;
        string con;
        public ExcelReader()
        {
            fileName = "a.xls";
            con = "Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=" + fileName + ";";
            ReadAndFill<DataItem>("DataSheet", DataList);
            ReadAndFill<AnotherDataItem>("AnotherDataSheet", AnotherDataList);
        }
    
        void ReadAndFill<T>(string sheetName, List<T> list)
        {
            DataTable table = this.FillDataTable(sheetName);
            this.FillDataList<T>(table, list);
            table.Clear();
        }
    
        DataTable FillDataTable(string sheetName)
        {
            string query = "SELECT * FROM [" + sheetName + "$]";
            OdbcConnection oCon = new OdbcConnection(con);
            OdbcCommand oCmd = new OdbcCommand(query, oCon);
            DataTable dataTable = new DataTable(sheetName);
            oCon.Open();
            try
            {
                OdbcDataReader rData = oCmd.ExecuteReader();
                dataTable.Load(rData);
                rData.Close();
                oCon.Close();
            }
            catch ( Exception )
            {
                oCon.Close();
            }
            return dataTable;
        }
    
    
        void FillDataList<T>(DataTable table, List<T> list)
        {
            list.Clear();
            if ( table.Rows.Count <= 0 )
                return;
            FieldInfo [] fields = typeof(T).GetFields();
            foreach ( DataRow row in table.Rows )
            {
                if ( row.IsNull(0) )
                {
                    //"Sheet " + table.TableName + " has a null column at index = " + index);
                    continue;
                }
                object o = Activator.CreateInstance(typeof(T));
                foreach ( FieldInfo field in fields )
                {
                    try
                    {
                        if ( row.Field<object>(field.Name) == null )
                            continue;
                        if ( field.FieldType.IsEnum )
                            field.SetValue(o, Enum.Parse(field.FieldType, Convert.ToString(row.Field<object>(field.Name)), true));
                        else
                            field.SetValue(o, Convert.ChangeType(row.Field<object>(field.Name), field.FieldType));
                    }
                    catch ( Exception e )
                    {
                        if ( e.GetType() == typeof(IndexOutOfRangeException) )
                        {
                            //There is no column named as " + field.Name + " at sheet " + table.TableName;
                        }
                        else
                        {
                            //Excel Reading Error at sheet " + table.TableName + " at index = " + index + " at field = " + field.Name + "\nException Message = " + e.Message;
                        }
                    }
                }
                list.Add(( T )o);
            }
        }
    }
    
    

    public by cicero81  100  0  4  0

    Find line number and member name via reflection

    This method allows to know the line number and the method name of the caller
    using System.Reflection;
    using System.Runtime.CompilerServices;
    
    public static void Fail(this object testClass, string message = "",
    			[CallerLineNumber] int lineNumber = 0,
    			[CallerMemberName] string caller = null)
    {
    	throw new FailTestException(string.Format("{0}.{1} failed at line {2} {3}", 
    		testClass.GetType().FullName, caller, lineNumber, message));
    }				

    public by lbottaro  22121  137  9  3

    How to programmatically create a Microsoft Word document in csharp

    This code shows how to simply create a doc using csharp and Microsoft Office Word library. 1) You need to add a reference to Microsoft.Office.Interop library in your project solution. 2) Add the following line to the end of the list of using directives: using Word = Microsoft.Office.Interop.Word; using System.Reflection; 3) Now you are
    private void button1_Click(object sender, EventArgs e)
            {
              object oMissing = System.Reflection.Missing.Value;
               object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
    
               //Start Word and create a new document.
               Word._Application oWord;
               Word._Document oDoc;
               oWord = new Word.Application();
               oWord.Visible = true;
               oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                   ref oMissing, ref oMissing);
    
               //Insert a paragraph at the beginning of the document.
               Word.Paragraph oPara1;
               oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
               oPara1.Range.Text = "Heading 1";
               oPara1.Range.Font.Bold = 1;
               oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
               oPara1.Range.InsertParagraphAfter();
    
               //Insert a paragraph at the end of the document.
               Word.Paragraph oPara2;
               object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
               oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
               oPara2.Range.Text = "Heading 2";
               oPara2.Format.SpaceAfter = 6;
               oPara2.Range.InsertParagraphAfter();
    
               //Insert another paragraph.
               Word.Paragraph oPara3;
               oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
               oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);
               oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:";
               oPara3.Range.Font.Bold = 0;
               oPara3.Format.SpaceAfter = 24;
               oPara3.Range.InsertParagraphAfter();
    
               //Insert a 3 x 5 table, fill it with data, and make the first row
               //bold and italic.
               Word.Table oTable;
               Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
               oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
               oTable.Range.ParagraphFormat.SpaceAfter = 6;
               int r, c;
               string strText;
               for (r = 1; r <= 3; r++)
                   for (c = 1; c <= 5; c++)
                   {
                       strText = "r" + r + "c" + c;
                       oTable.Cell(r, c).Range.Text = strText;
                   }
               oTable.Rows[1].Range.Font.Bold = 1;
               oTable.Rows[1].Range.Font.Italic = 1;
    
               //Add some text after the table.
               Word.Paragraph oPara4;
               oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
               oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);
               oPara4.Range.InsertParagraphBefore();
               oPara4.Range.Text = "And here's another table:";
               oPara4.Format.SpaceAfter = 24;
               oPara4.Range.InsertParagraphAfter();
    
               //Insert a 5 x 2 table, fill it with data, and change the column widths.
               wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
               oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);
               oTable.Range.ParagraphFormat.SpaceAfter = 6;
               for (r = 1; r <= 5; r++)
                   for (c = 1; c <= 2; c++)
                   {
                       strText = "r" + r + "c" + c;
                       oTable.Cell(r, c).Range.Text = strText;
                   }
               oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2
               oTable.Columns[2].Width = oWord.InchesToPoints(3);
    
               //Keep inserting text. When you get to 7 inches from top of the
               //document, insert a hard page break.
               object oPos;
               double dPos = oWord.InchesToPoints(7);
               oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
               do
               {
                   wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                   wrdRng.ParagraphFormat.SpaceAfter = 6;
                   wrdRng.InsertAfter("A line of text");
                   wrdRng.InsertParagraphAfter();
                   oPos = wrdRng.get_Information
                                  (Word.WdInformation.wdVerticalPositionRelativeToPage);
               }
               while (dPos >= Convert.ToDouble(oPos));
               object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
               object oPageBreak = Word.WdBreakType.wdPageBreak;
               wrdRng.Collapse(ref oCollapseEnd);
               wrdRng.InsertBreak(ref oPageBreak);
               wrdRng.Collapse(ref oCollapseEnd);
               wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
               wrdRng.InsertParagraphAfter();
    
               //Insert a chart.
               Word.InlineShape oShape;
               object oClassType = "MSGraph.Chart.8";
               wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
               oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing,
                   ref oMissing, ref oMissing, ref oMissing,
                   ref oMissing, ref oMissing, ref oMissing);
    
               //Demonstrate use of late bound oChart and oChartApp objects to
               //manipulate the chart object with MSGraph.
               object oChart;
               object oChartApp;
               oChart = oShape.OLEFormat.Object;
               oChartApp = oChart.GetType().InvokeMember("Application",
                   BindingFlags.GetProperty, null, oChart, null);
    
               //Change the chart type to Line.
               object[] Parameters = new Object[1];
               Parameters[0] = 4; //xlLine = 4
               oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,
                   null, oChart, Parameters);
    
               //Update the chart image and quit MSGraph.
               oChartApp.GetType().InvokeMember("Update",
                   BindingFlags.InvokeMethod, null, oChartApp, null);
               oChartApp.GetType().InvokeMember("Quit",
                   BindingFlags.InvokeMethod, null, oChartApp, null);
               //... If desired, you can proceed from here using the Microsoft Graph 
               //Object model on the oChart and oChartApp objects to make additional
               //changes to the chart.
    
               //Set the width of the chart.
               oShape.Width = oWord.InchesToPoints(6.25f);
               oShape.Height = oWord.InchesToPoints(3.57f);
    
               //Add text after the chart.
               wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
               wrdRng.InsertParagraphAfter();
               wrdRng.InsertAfter("THE END.");
    
               //Close this form.
               this.Close();
    }
    

    public by Geometry  1218  0  4  0

    Copy: Copy properties from one IOperationResult to another. Does not use reflection. Ony LCD properties are copied

    Copy properties from one IOperationResult to another. Does not use reflection. Ony LCD properties are copied
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    /// <summary>
    /// Copy properties from one IOperationResult to another.  Does not use reflection.
    /// Ony LCD properties are copied
    /// </summary>
    /// <param name="target"></param>
    public static void Copy(this IOperationResult source, IOperationResult target)
    {
    	target.Message = source.Message;
    	target.Success = source.Success;
    	target.Exception = source.Exception;
    	target.StatusCode = source.StatusCode;
    }

    public by Geometry  1159  0  5  0

    Copy: Copy properties from one IOperationResult to another. Does not use reflection. Ony LCD properties are copied

    Copy properties from one IOperationResult to another. Does not use reflection. Ony LCD properties are copied
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    /// <summary>
    /// Copy properties from one IOperationResult to another.  Does not use reflection.
    /// Ony LCD properties are copied
    /// </summary>
    /// <param name="target"></param>
    public static void Copy(this IOperationResult source, IOperationResult target)
    {
    	target.Message = source.Message;
    	target.Success = source.Success;
    	target.Exception = source.Exception;
    	target.StatusCode = source.StatusCode;
    }

    public by Geometry  1069  0  4  0

    PassOrFail: Copy properties from one IOperationResult to another. Does not use reflection. Ony LCD properties are copied

    Copy properties from one IOperationResult to another. Does not use reflection. Ony LCD properties are copied
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    /// <summary>
    /// Copy properties from one IOperationResult to another.  Does not use reflection.
    /// Ony LCD properties are copied
    /// </summary>
    /// <param name="target"></param>
    public static IOperationResult PassOrFail(this IOperationResult source, bool success, string message = "", Exception ex = null)
    {
    	return success ? Pass(source) : Fail(source, message, ex);
    }

    public by Geometry  990  0  3  0

    Create: Creates an instance of the specified type using a generated factory to avoid using Reflection.

    Creates an instance of the specified type using a generated factory to avoid using Reflection. The type to be created. The newly created instance.
    C#
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Text;
    using System.Threading;
    using System.Linq.Expressions;
    
    /// <summary>
    /// Creates an instance of the specified type using a generated factory to avoid using Reflection.
    /// </summary>
    /// <typeparam name="T">The type to be created.</typeparam>
    /// <returns>The newly created instance.</returns>
    public static T Create<T>()
    {
    	return TypeFactory<T>.Create();
    }
    • Public Snippets
    • Channels Snippets